NodeJS + MongoDB:insertOne() - 从 result.ops 中获取插入的文档 [英] NodeJS + MongoDB: insertOne() - get the inserted document from result.ops

查看:14
本文介绍了NodeJS + MongoDB:insertOne() - 从 result.ops 中获取插入的文档的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我看到的文档中,我们可以使用返回的 insertOneWriteOpResultObject.ops 来检索插入的文档.(Docs),但是在做的时候所以我回来了 undefined.

In the docs I see we can use the returned insertOneWriteOpResultObject.ops to retrieve the document inserted. (Docs), but when doing so I get back undefined.

要重现的代码:

const collection = db.collection("testcollection");
collection.insertOne({"name": "Test_Name", "description": "Test desc."},
(err, result) => {

    console.log("After Insert:
");
    console.log(result.ops); //undefined but should return the document
    
    collection.find({}).toArray((err, docs) => {
        
        console.log("Found:
");
        console.log(docs);

        db.dropCollection("testcollection", (err, result) => {

            client.close();
        });
    });
});

推荐答案

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

Check version of MongoDB Node.js Driver with command npm list mongodb. If it is version 4 then you can not access result.ops. In version 4 insertOne returns insertOneResult that have only 2 properties: acknowledged and insertedId.

这篇关于NodeJS + MongoDB:insertOne() - 从 result.ops 中获取插入的文档的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆