Firestore:更新父级后如何将文档添加到子集合 [英] Firestore: How to add a document to a subcollection after updating parent

查看:53
本文介绍了Firestore:更新父级后如何将文档添加到子集合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在为IOT类型的应用程序构建一个快速的API.结构是,我有一个带有 latestValue1 latestVoltage 值的传感器文档.每个传感器文档还具有读数集合(例如每小时记录一次).

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.)

Set函数可以很好地更新 latestValue1 latestVoltage ,但是我正在努力找出如何创建读数集合并向其中添加文档的方法.下面的代码给我 TypeError:document.collection不是函数

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?

推荐答案

set()不返回DocumentReference对象.它返回一个您应该等待的承诺.

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

如果要建立对子集合的引用,则应链接调用以到达该子集合. add()还会返回一个您应该等待的承诺.

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

这篇关于Firestore:更新父级后如何将文档添加到子集合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆