Node.js + MongoDB: insert one and return the newly inserted document
UPDATE 2021: This approach no longer works with the MongoDB driver 4.x. The return result of the insertOne only contains an ID and acknowledgement flag: https://mongodb.github.io/node-mongodb-native/4.1/interfaces/InsertOneResult.html
With this change, there is NO way to accomplish the required behaviour. One should either do another DB request or combine the returned insertId and original object data.
The response
result contains information about whether the command was successful or not and the number of records inserted.
If you want to return inserted data, you can try response.ops
, for example:
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
}
});
Official documentation for insertOne
:
http://mongodb.github.io/node-mongodb-native/3.1/api/Collection.html#insertOne
The callback
type:
http://mongodb.github.io/node-mongodb-native/3.1/api/Collection.html#~insertOneWriteOpCallback
The result
type:
http://mongodb.github.io/node-mongodb-native/3.1/api/Collection.html#~insertOneWriteOpResult
The following code worked for me, in MongoDB version 2.2.33.
db.collection("sample_collection").insertOne({
field1: "abcde"
}, (err, result) => {
if(err) console.log(err);
else console.log(result.ops[0].field1)
}