Reputation: 35557
I have the following MongoDB query and I am using the mongodb node.js driver to connect:
db.collection('employee').insertOne(employeeObj).then(result => {
console.log(result);
res.send(result);
}).catch(function (err) {
console.log("ERROR: ", err);
});
From the above, I would like to obtain the newly created employee's Object _Id but when I console log the result, I get:
Object { n: 1, ok: 1 }
Using the above query, how can I also include the new _id
just created within the returned result?
Upvotes: 0
Views: 2132
Reputation: 14896
The result object should contain a insertedId
property which is driver generated ObjectId
for the insert operation.
Try to log result.insertedId
to check the id, and also you should have the inserted object in the ops
property.
Upvotes: 2
Reputation: 3543
The _id
field would be added to the employeeObj
once it is added to the collection.
This is from the docs:
insertOne(doc, options, callback)
Inserts a single document into MongoDB. If documents passed in do not contain the _id field, one will be added to each of the documents missing it by the driver, mutating the document. This behavior can be overridden by setting the forceServerObjectId flag.
Just change the code to:
db.collection('employee').insertOne(employee).then(result => {
console.log(employee._id);
res.send({employee, result});
}).catch(function (err) {
console.log("ERROR: ", err);
});
This might be helpful too.
Upvotes: 0