Home > Back-end >  Firebase firestore is there a way to write data from an array into a document and then subcollection
Firebase firestore is there a way to write data from an array into a document and then subcollection

Time:07-22

I'm new to firebase in general and am trying to write parts of an array into a document and its remaining data in a document in a subcollection. Here is what I've done:

let db = admin.firestore();    
db.collection("User")
          .doc(fields.user)
          .collection("Address")
          .doc(fields.address)
          .set({
            User: fields.user,
            Address: fields.address,
          })
          .then(
            db.collection("User")
              .doc(fields.user)
              .collection("Address")
              .doc(fields.address)
              .collection("Orders")
              .doc(fields.ID)
              .set({
                ID: fields.ID,
              });

My biggest question is if there is a better way to do this? Here its a small sample but for cases it can get very long. Thanks in advance for any help.

CodePudding user response:

I often prefer constructing longer paths using string interpolation, which would lead to:

db.doc(`User/${fields.user}/Address/${fields.address}`)
  .set({
    User: fields.user,
    Address: fields.address,
  })
  .then(
    db.doc(`User/${fields.user}/Address/${fields.address}/Orders/${fields.ID}`)
      .set({
        ID: fields.ID,
      });

Aside from that, you probably want to do this in a batched write so that either both of the writes succeed, or neither of them does.

CodePudding user response:

if you have all the data in the first time. you can create your object with subcollections and then set it in one request

var obj = {
        User: fields.user,
        Address: fields.address,
        Orders: {
          ID: fields.ID,
        }
}
db.collection("User").doc(fields.user).set(obj)
.then(() => {
    console.log("Document successfully written!");
})
.catch((error) => {
    console.error("Error writing document: ", error);
});
  • Related