Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Node + Mongoose: Get last inserted ID?

I want to retrieve the last inserted _id, using mongoose as MongoDB wrapper for node.js. I've found the following tutorial, but I can't change any node modules because the app runs on a public server:

Getting "Last Inserted ID" (hint - you have to hack Mongoose)

Any other ideas? This what I want to do:

  • Insert new user
  • Get user's _id value
  • Set a new session based on user's id
  • Redirect to /

Thanks!

like image 726
trnc Avatar asked May 20 '11 15:05

trnc


3 Answers

I'm using mongoose version 1.2.0 and as soon as I created a new instance of a mongoose model, the _id is already set.

coffee> u = new User()
[object Object]
coffee> u._id
4dd68fc449aaedd177000001

I also verified that after I call u.save() the _id remains the same. I verified via MongoHub that this is indeed the real ID saved into MongoDB.

like image 88
Peter Lyons Avatar answered Oct 11 '22 11:10

Peter Lyons


If you explicitly declare

    _id: Schema.ObjectId

for your model, then the ObjectId will not be available after new or save. This is probably a bug.

like image 39
Kari-S Avatar answered Oct 11 '22 10:10

Kari-S


If you're looking to get the last inserted _id of a sub object, then create the object, and add it to the item. Here's an example in NowJS using MongoDB and Mongoose (to add some schema sugar) which then converts the result to JSON to send back to the client:

                var nowRoomID = this.now.room;
                var Conversation = mongoose.model('Conversation');
                Conversation.findById(convID, function(error, conversation) {
                    var Blip = mongoose.model('Blip');
                    var createdBlip = new Blip();
                    createdBlip.author= nowUserName;
                    createdBlip.authorid = parsed.authorid;
                    createdBlip.body = revisedText;
                    createdBlip.created_at = new Date();
                    createdBlip.modified_at = new Date();

                    conversation.blips.push(createdBlip);
                    parsed._id = createdBlip._id;  //NOTE: ID ACCESSED HERE
                    message = JSON.stringify(parsed);

                    conversation.save(function (err) {
                        if (!err) {
                            console.log('Success - saved a blip onto a conversation!');
                            nowjs.getGroup(nowRoomID).now.receiveMessage(nowUserName, message);
                        }

                    });
like image 36
JayCrossler Avatar answered Oct 11 '22 10:10

JayCrossler