Search code examples
javascriptnode.jsfirebasegoogle-cloud-firestorefirebase-security

Get Firestore parent doc ID in subcollection


Is it possible to retrieve the parent document ID within a sub-collection?

The user can create a bot, which will itself contain a history linked to this bot. To list this history against the bot ID., i need to be able to get the ID of the parent (that of the bot's document).

enter image description here

The minimal logic in cloud functions:

try {
  await db.collection("bots").add({
    createdBy: uid,
    createdAt: new Date(),
  });

  // create orders_history subcollection 
  await db.collection("bots").doc().collection("order_history").add({
    createdBy: uid, // user uid
    botId: context.ref.parent, // how i can get parent doc ID (7aIvUIjC...) ?
  })
} catch (e) {
  ...
}

My security rule should also check if botId is equal to the id of the parent document (7aIvUIjC....).

match /{path=**}/order_history/{id} {
  allow read, write: if request.auth != null id == resource.data.botId;
}

Solution

  • If you look at the second snippet in the documentation on adding a document, you can see that it logs the ID of the new document:

    // Add a new document with a generated id.
    const res = await db.collection('cities').add({
      name: 'Tokyo',
      country: 'Japan'
    });
    
    console.log('Added document with ID: ', res.id);
    

    You can use the same logic, using the return value from the call to add, to get the ID that is needed for your subcollection:

    const res = await db.collection("bots").add({
      createdBy: uid,
      createdAt: new Date(),
    });
    
    // create orders_history subcollection 
    await db.collection("bots").doc(res.id).collection("order_history").add({
      createdBy: uid, // user uid
      botId: context.ref.parent, // how i can get parent doc ID (7aIvUIjC...) ?
    })