Allen Rohner
Allen Rohner

Reputation: 1118

How to get last inserted id using the JS api?

Using the javascript api for MongoDB, how do you get the ID of the last inserted object? i.e.

obj = {a: 1, b: 2};
db.foo.insert(obj);

How do I get the ID for obj?

Upvotes: 13

Views: 5265

Answers (4)

Nico
Nico

Reputation: 4416

If you run

db.collection("venues").insert( {name: "test3", FSid: "test3"}, function( err, ret) {
   console.log( ret )
})

it returns

{ result: { ok: 1, n: 1 },
  ops: [ { name: 'test3', FSid: 'test3', _id: 57cb0a1162cecfe636df6fc1 } ],
  insertedCount: 1,
  insertedIds: [ 57cb0a1162cecfe636df6fc1 ] }

So you can get your ids along with all inserted objects through:

ret.ops[0]._id

or straight

ret.insertedIds[0]

Upvotes: 1

user2182434
user2182434

Reputation: 1

If you insert the data like this:

    var temptodo = new User({
        title: data.todo.text,
        email: socket.handshake.email,
        created_at: Date.now(),
        completed: false,
        sid: socket.handshake.sid
    });
    temptodo.save( function(error, User){

            console.log("this is the id for the new todo. "+User._id);
            console.log('Todo saved in database with sid: '+socket.handshake.sid);
    });

Then you can grab the _id like this: console.log("this is the id for the new todo. "+User._id);

Upvotes: 0

zawdd
zawdd

Reputation: 321

Now,the mongo native js api supports this. You can get the last id like this:

collection.insert(line, {w : 1}, function(err, inserted) {
  inserted[0]._id
}

insert sets the _id property on the inserted object, but it looks like you have to wait for the object to return. The best documentation I've found for this is (unfortunately) in the source code:

https://github.com/mongodb/node-mongodb-native/blob/master/lib/mongodb/collection.js

Upvotes: 0

Allen Rohner
Allen Rohner

Reputation: 1118

The people on #mongodb were helpful. The JS API doesn't currently support this, but you can use your own id. To generate a "normal" id, do _id: new ObjectId(). So the example in my question would be:

id = new ObjectId();
obj = {a: 1, b: 2, _id: id};
db.foo.insert(obj);

Upvotes: 25

Related Questions