Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 go.

This is what I'm currently using:

db.collection('mycollection').insertOne(options, function (error, response) {     ... }); 
like image 309
evilReiko Avatar asked Nov 23 '16 14:11

evilReiko


People also ask

What does MongoDB insert return?

Returns: A document containing: A boolean acknowledged as true if the operation ran with write concern or false if write concern was disabled. A field insertedId with the _id value of the inserted document.

How do I insert one document into MongoDB?

In MongoDB, insertOne() method inserts a document into the collection. This method inserts only one document at a time. Using this method you can also create a collection by inserting documents. You can insert documents with or without _id field.

What is the difference between insert and insertOne in MongoDB?

With insertOne you can insert one document into the collection. insertMany accepts an array of documents and these are inserted. The insert (the method from older versions) takes a single document by default, and there is an option to insert multiple documents supplied as an array.

Which method of Mongoose helps to insert one record of a specific model into a collection?

The create() method is similar to the insert() method. It is used to insert a single document in a collection. Let's understand the create() method with the help of an example.


1 Answers


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

like image 108
Shaishab Roy Avatar answered Oct 11 '22 03:10

Shaishab Roy