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\').i
Posting this as this might be helpful for someone. You can find the updated object like this:
await req.db
.collection('users')
.insertOne({ email, password: hashedPassword, name })
.then(({ ops }) => ops[0]);
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)
}
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
You could use mongoose to do this. With the save
method you can insert a document and return it on success. Here is an example from the mongoose documentation:
product.save(function (err, product, numAffected) {
if (err) {
// Handle error...
} else {
// Do something with the returned document...
}
})
Try This
try {
let collection = db.collection('collection_name'); let { ops: inserted } =
await collection.insertOne({ data: object });
// can access array of inserted record like :
console.log(inserted)
} catch (error) {
// log errors
}
You could use mongojs to do this.
db.collection('mycollection').save(doc, function(error, response){
// response has _id
})