Firestore: How to add a document to a subcollection after updating parent

佐手、 提交于 2021-02-10 23:59:20

问题


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 collection of readings (an hourly log, let's say.)

The Set function works fine to update latestValue1 and latestVoltage, but I'm struggling to work out how to create the readings collection and add a document to it- the code below gives me TypeError: document.collection is not a function

app.put('/api/update/:item_id', (req, res) => {
    (async () => {
        try {
            const document = db.collection('sensors').doc(req.params.item_id).set({
                latestValue1: req.body.value1,
                latestVoltage: req.body.voltage
            }, {merge: true});
            await document.collection('readings').add({
                value1: req.body.value1,
                voltage: req.body.voltage
            });
            return res.status(200).send();
        } catch (error) {
            console.log(error);
            return res.status(500).send(error);
        }
    })();
});

How can I fix the code above to correctly add a new document to the readings collection?


回答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
});


来源:https://stackoverflow.com/questions/64779618/firestore-how-to-add-a-document-to-a-subcollection-after-updating-parent

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