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) { ... });
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.
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With