Hairul Akli
Hairul Akli

Reputation: 11

return object id after save mongodb, can you help me?

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

Answers (2)

Lanil Marasinghe
Lanil Marasinghe

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

tim
tim

Reputation: 378

From the mongodb docs:

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

The following code works for me:

db.collection('item').insertOne(itemToInsert,(err, item) => console.log(item.insertedId))

Upvotes: 1

Related Questions