evilReiko evilReiko - 11 months ago 78
Node.js Question

Node.js + MongoDB: insert one and return the newly inserted document

I'm wondering if there is a way to insert new document and return it in one in one go.

This is what I'm currently using:

db.collection('mycollection').insertOne(options, function (error, response) {
...
});

Answer Source

response result contain information of success or not and number of record inserted. but if you want to return inserted data then can try response.ops

db.collection('mycollection').insertOne(doc, function (error, response) {
    if(error) {
        console.log('Error occurred while inserting');
       // return 
    } else {
       console.log('inserted record', response.ops[0]);
      // return 
    }
});