Reputation: 11
how to retrieve objectid after save ? iam using mongodb, expressjs. i not use mongoose, can you help me
var dataID = "";
mongo.connect(urlMongo,function(err,db){
assert.equal(null,err);
db.collection('item').insertOne(item,function(){
assert.equal(null,err);
});
});
res.send(dataID);
Upvotes: 1
Views: 2185
Reputation: 2915
var dataID = "";
mongo.connect(urlMongo,function(err,db){
assert.equal(null,err);
db.collection('item').insertOne(item,function(err, res){
dataID = res.ops[0]._id
assert.equal(null,err);
});
});
res.send(dataID);
Use res.ops[0]._id to get the ID of inserted object
Upvotes: 0
Reputation: 378
From the mongodb docs:
InsertOne returns a document containing:
The following code works for me:
db.collection('item').insertOne(itemToInsert,(err, item) => console.log(item.insertedId))
Upvotes: 1