【问题标题】:NodeJS + MongoDB: insertOne() - get the inserted document from result.opsNodeJS + MongoDB:insertOne() - 从 result.ops 中获取插入的文档
【发布时间】:2021-07-16 16:03:37
【问题描述】:

在我看到的文档中,我们可以使用返回的 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();
        });
    });
});

【问题讨论】:

    标签: node.js mongodb nosql


    【解决方案1】:

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

    【讨论】:

    • 您知道在第 4 版中插入后插入文档的正确方法是什么吗?查询它?
    • 看起来没有别的选择,只能查询它
    • 这太疯狂了!他们为什么要删除 ops 并对此保持沉默?
    • result.insertedId,这行不通?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-16
    • 1970-01-01
    • 2018-09-04
    • 2017-02-17
    • 1970-01-01
    • 2015-09-17
    相关资源
    最近更新 更多