Skip to content Skip to sidebar Skip to footer

Firestore: How To Add A Document To A Subcollection After Updating Parent

I'm building out a quick API for an IOT type app. The structure is that I have a sensor document with latestValue1 and latestVoltage values. Each sensor document also has a collect

Solution 1:

set() doesn't return a DocumentReference object. It returns a promise which you should await.

await db.collection('sensors').doc(req.params.item_id).set({
    latestValue1: req.body.value1,
    latestVoltage: req.body.voltage
}, {merge: true});

If you want to build a reference to a subcollection, you should chain calls to get there. add() also returns a promise that you should await.

await db.collection('sensors').doc(req.params.item_id)collection('readings').add({
    value1: req.body.value1,
    voltage: req.body.voltage
});

FYI you can also declare the entire express handler function async to avoid the inner anonymous async function:

app.put('/api/update/:item_id', async (req, res) => {
    // await in here
});

Post a Comment for "Firestore: How To Add A Document To A Subcollection After Updating Parent"