skip to Main Content

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.

2

Answers


  1. 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.

    Login or Signup to reply.
  2. 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);
    });
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search