【问题标题】:Using MongoDB Stitch webhook service function, how can I convert the returned "insertedId" to string?使用 MongoDB Stitch webhook 服务函数,如何将返回的“insertedId”转换为字符串?
【发布时间】:2020-03-17 16:09:37
【问题描述】:

我正在为一个简单的 CRUD 应用程序创建 MongoDB Stitch http 服务(使用 3rd Party Services > Incoming Webhooks > Function Editor),我正在尝试 insertOne() 文档,然后将文档 ID 作为字符串返回。

插入按预期工作,我等待结果并将其存储在变量中。

const result = await collection.insertOne(payload.query)
const id = result.insertedId

问题是试图将此id 转换为字符串。我猜这是因为我对 MongoDB 扩展 JSON 和 BSON 类型等缺乏了解。我已经阅读了我认为可以在此处提供解决方案的所有文档部分。

我尝试了以下方法将返回值转换为字符串:

id.toString() // logs as a string, but is an object { $oid: '507c7f79bcf86cd7994f6c0e' }
id.valueOf() // logs as a string, but is an object { $oid: '507c7f79bcf86cd7994f6c0e' }
id['$oid'] // undefined
Object.values(id.insertedId) // throws error: {"message":"'values' is not a function"}
id.str // undefined
result.str // undefined

不确定还有什么可以尝试的,如果有人能在此处指出正确的方向以提供解决方案,我将不胜感激。

提前谢谢你。

【问题讨论】:

    标签: javascript mongodb mongodb-query mongodb-stitch


    【解决方案1】:

    在注意到文档的这一部分后找到了解决方案: MONGODB STITCH > Functions > Reference > JSON & BSON

    const result = await collection.insertOne(payload.query)
    const id = JSON.stringify(
      JSON.parse(
        EJSON.stringify(result.insertedId)
      ).$oid
    ).replace(/\W/g,'');
    

    将文档的 id 转换为字符串似乎有点 hacky,但它现在可以工作。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-10-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-02-21
      • 2015-07-04
      相关资源
      最近更新 更多