[英]nodejs mongodb - how to return the inserted document using insertOne
[英]NodeJS + MongoDB: insertOne() - get the inserted document from result.ops
在我看到的文檔中,我們可以使用返回的 insertOneWriteOpResultObject.ops 來檢索插入的文檔。 ( 文檔),但是這樣做時我會返回undefined
。
重現代碼:
const collection = db.collection("testcollection");
collection.insertOne({"name": "Test_Name", "description": "Test desc."},
(err, result) => {
console.log("After Insert:\n");
console.log(result.ops); //undefined but should return the document
collection.find({}).toArray((err, docs) => {
console.log("Found:\n");
console.log(docs);
db.dropCollection("testcollection", (err, result) => {
client.close();
});
});
});
使用命令npm list mongodb
檢查 MongoDB Node.js 驅動程序的版本。 如果是第 4 版,則無法訪問result.ops
。 在版本 4 中, insertOne返回只有 2 個屬性的insertOneResult :accepted 和 insertedId。
4.x 中有一些變化。 您可以參考下面的鏈接。 https://github.com/mongodb/node-mongodb-native/blob/HEAD/etc/notes/CHANGES_4.0.0.md
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.