我正在为一个简单的 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'] // undefinedObject.values(id.insertedId) // throws error: {"message":"'values' is not a function"}id.str // undefinedresult.str // undefined不知道还有什么可以尝试的,如果有人能在这里指出我正确的方向以提供解决方案,我将不胜感激。先感谢您。
1 回答
湖上湖
TA贡献2003条经验 获得超2个赞
注意到文档的这一部分后找到了解决方案: 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,但它现在可以工作。
添加回答
举报
0/150
提交
取消
