Home > OS >  Can I post a same document to 2 different collections in Firebase?
Can I post a same document to 2 different collections in Firebase?

Time:10-26

I am trying to post the same document with same ID's to 2 different collections I tried this:

 db.collection("users").add({
    name: "userName",
    lastName: "userLastName"
})
.then(userDocRef => {
    userDocRef.collection("favFood").add({
        favDrink: "userDrink",
        favDessert: "userDesert",
 })

 // then post the same information to different collection
 .then(userDocRef => {
    db.collection("users__2").add({
        name: "userName",
        lastName: "userLastName"
    }).then(userDocRef => {
        userDocRef.collection("favFood").add({
            favDrink: "userDrink",
            favDessert: "userDesert",
    })
 })

});   

and It worked Everything was the same But the ID was different is Possible to Have the same ID's?

CodePudding user response:

By using the add() method you generate a new Firestore document ID, this is why the Firestore document IDs are different.

You should use the doc() method without specifying any path: "an automatically-generated unique ID will be used for the returned DocumentReference". Then you use this document ID as follows, since there is no problem to use the same ID in two different collections.

const userDocRef = db.collection('users').doc();
userDocRef
.set({
    name: 'userName',
    lastName: 'userLastName',
})
.then(() => {
    return userDocRef.collection('favFood').add({
    favDrink: 'userDrink',
    favDessert: 'userDesert',
    });
})
.then(() => {
    return db.collection('users__2').doc(userDocRef.id).set({
    name: 'userName',
    lastName: 'userLastName',
    });
})
.then(() => {
    db.collection('users__2')
    .doc(userDocRef.id)
    .collection('favFood')
    .add({
        favDrink: 'userDrink',
        favDessert: 'userDesert',
    });
})
.catch((error) => {
    console.log(error);
});
  • Related