Cloud Firestore: Add collection and sub collection in one go

为君一笑 提交于 2021-01-28 06:44:21

问题


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:


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.



来源:https://stackoverflow.com/questions/56979266/cloud-firestore-add-collection-and-sub-collection-in-one-go

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!