Node + Mongoose: Get last inserted ID?

By : Tronic
Source: Stackoverflow.com
Question!

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!

By : Tronic


Answers

With MongoDB, if you don't explicitly set a document's _id value then the client driver will automatically set it to an ObjectId value. This is different from databases that might generate IDs on the server and need another query to retrieve it, like with SQL Server's scope_identity() or MySQL's last_insert_id().

This allows you to insert data asynchronously because don't need to wait for the server to return an _id value before you continue.

So, as shown is Peter's answer, the _id is available before the document is saved to the database.



Check below url

http://mongodb.github.io/node-mongodb-native/markdown-docs/insert.html

you will find following code in given url

    var document = {name:"David", title:"About MongoDB"};
   collection.insert(document, {w: 1}, function(err, records){
  console.log("Record added as " records[0]._id);
});
By : Dineshaws


I just get the id from the document passed to the callback, since save returns the saved document.



This video can help you solving your question :)
By: admin