Cloud Firestore: Add collection and sub collection in one go

Reading the documentation I can't see a way if this is possible in a sensible way.

I'm trying to create a document team with a sub document of member.

And what I'm really trying to achieve is an in-complex way of structuring read/writes/updates on collections and sub collections.

async createTeam(newTeam, foundingTeamMember) {
    const teams = db.collection('teams');
    const teamRef = await db.collection('teams').add(newTeam);
    const memberRef = await teams.doc(companyRef.id)
      .collection('members').add(foundingTeamMember);

    return({
       teamId: teamRef.id,
       memberId: memberRef.id,
    });
}

In particular is there a means of returning teamId and memberId without needing to use async / await?

Something like:

  db
    .collection('teams')

    .add(newTeam)
    .collection('members')
    .add(foundingTeamMember).then(/* return collection parent ID */)

1 answer

  • answered 2019-07-10 23:19 Doug Stevenson

    The random IDs for new documents are always generated on the client. You can use the doc() method on a CollectionReference with no parameters to generate a reference to a document that has a random ID without actually adding the document. You can then work with that reference's id property immeidately, and create the document later.