![](/img/trans.png)
[英]Node.js + MongoDB: insert one and return the newly inserted document
[英]Return Inserted Document in MongoDb ( Node.js )
我需要向 MongoDB 插入一个文档并返回新插入的文档。 我使用了 db.collection('collection__name').insertOne('data to be insert').then((res)=>{ res.send(res.ops[0]) })
错误:未定义操作。
insertOne 只返回插入的文档的_id,而不是整个文档☹,但之前它用于返回整个文档。 我使用 mongoclient 而不是 mongoose,在 mongoose 中它返回整个文档,但我不喜欢使用 mongoose。
他们从 mongo 4.0 开始删除了 ops 字段,你可以在这里找到架构: https : //mongodb.github.io/node-mongodb-native/4.0/interfaces/insertoneresult.html#insertedid
我刚刚查了 mongoose 的源代码,他们实际上是根据 insertId 字段调用 findOne :
const promise = collection.insertOne({ foo: 'bar' }, {})
.then(result =>
collection.findOne({ _id: result.insertedId })
).then(doc => {
assert.strictEqual(doc.foo, 'bar');
});
似乎唯一的解决方案是使用旧的库版本(没有打字稿)或使用返回的 id 字段调用 findOne 。 我只是遇到了同样的问题并添加了额外的 findOne 调用,因为我不想放弃打字稿。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.