NodeJS + MongoDB:insertOne()-从result.ops中获取插入的文档

eimct9ow  于 2023-04-05  发布在  Go
关注(0)|答案(2)|浏览(123)

在文档中,我们可以使用返回的insertOneWriteOpResultObject.ops来检索插入的文档.(Docs),但这样做时,我会得到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();
        });
    });
});
u4vypkhs

u4vypkhs1#

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

相关问题