首页 > 解决方案 > NodeJS + MongoDB:insertOne() - 从 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();
        });
    });
});

标签: node.jsmongodbnosql

解决方案


使用命令检查 MongoDB Node.js 驱动程序的版本npm list mongodb。如果是版本 4 则无法访问result.ops。在版本 4中, insertOne返回只有 2 个属性的 insertOneResult:accepted 和 insertedId


推荐阅读