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 /


5/20/2011 11:42:44 PM

Accepted Answer

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

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

5/20/2011 4:05:15 PM

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow