【问题标题】:Firebase: update document by ID stored in bodyFirebase:通过存储在正文中的 ID 更新文档
【发布时间】:2020-11-11 22:29:26
【问题描述】:

我正在构建一个简单的 Firebase API 来更新一个简单的值。我正在向 url appname.cloudfunctions.net/app/api/update/ 发送一个 PUT 请求,其中包含要在正文中更新的文档的 ID:

{
    "id": 10,
    "value1": 11
}

然后我的函数是这样的:

app.put('/api/update/', async (req, res) => {
    try {
        const sensorId = req.body.id;
        await db.collection('sensors').doc(sensorId).set({
            latestUpdateTimestamp: admin.firestore.FieldValue.serverTimestamp(),
            latestValue1: req.body.value1,
        }, {merge: true});
        return res.status(200).send();
    } catch (error) {
        console.log(error);
        console.log(req.body);
        return res.status(500).send(error);
    }
});

问题是,我收到一个错误:错误:参数“documentPath”的值不是有效的资源路径。路径必须是非空字符串。 请注意,console.log(req.body) 显示正文中的正确 ID 和 value1。

我该如何解决这个问题?

【问题讨论】:

  • 尝试console.log(req.body) 看看会出现什么——该错误表明req.body.idundefined
  • 是的,工作正常,ID 显示在那里。如果有帮助,这是对此处另一个问题的代码的轻微修改:stackoverflow.com/questions/64779618/…
  • 它说Path must be a non-empty string"id": 10。这可能是为什么?
  • @windowsill 欢呼,是的,现在解决了,必须添加 .toString()

标签: firebase


【解决方案1】:

我的 const sensorId 是作为数字发送的,我需要将其更改为字符串以使其工作:

const sensorId = req.body.id.toString();

【讨论】:

    猜你喜欢
    • 2016-04-01
    • 1970-01-01
    • 2011-03-19
    • 2019-10-16
    • 2015-12-30
    • 2021-05-06
    • 2013-12-04
    • 1970-01-01
    • 2019-02-06
    相关资源
    最近更新 更多