Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NodeJS + MongoDB: insertOne() - get the inserted document from result.ops

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.

Code to reproduce:

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();
        });
    });
});
like image 737
l000p Avatar asked Dec 30 '22 13:12

l000p


1 Answers

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.

like image 58
zswqa Avatar answered Apr 23 '23 04:04

zswqa