我正在为物联网类型的应用程序构建一个快速API。结构是我有一个传感器文件 和 最晚电压
Set函数可以很好地进行更新 和 最晚电压 ,但我正在努力解决如何创建readings集合并向其中添加文档-下面的代码为我提供了 TypeError:document.collection不是函数
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); } })(); });
如何修复上面的代码以正确地将新文档添加到readings集合?
set() 不返回DocumentReference对象。它回报了一个你应该等待的承诺。
set()
await db.collection('sensors').doc(req.params.item_id).set({ latestValue1: req.body.value1, latestVoltage: req.body.voltage }, {merge: true});
如果要构建对子集合的引用,应该链接调用以到达该子集合。 add()
add()
await db.collection('sensors').doc(req.params.item_id)collection('readings').add({ value1: req.body.value1, voltage: req.body.voltage });
仅供参考,您还可以将整个express handler函数声明为async,以避免内部匿名异步函数:
app.put('/api/update/:item_id', async (req, res) => { // await in here });