How do I get the objectID after I save an object in Mongoose?

node.jsMongodbMongoose

node.js Problem Overview


var n = new Chat();
n.name = "chat room";
n.save(function(){
    //console.log(THE OBJECT ID that I just saved);
});

I want to console.log the object id of the object I just saved. How do I do that in Mongoose?

node.js Solutions


Solution 1 - node.js

This just worked for me:

var mongoose = require('mongoose'),
      Schema = mongoose.Schema;

mongoose.connect('mongodb://localhost/lol', function(err) {
    if (err) { console.log(err) }
});

var ChatSchema = new Schema({
    name: String
});

mongoose.model('Chat', ChatSchema);

var Chat = mongoose.model('Chat');

var n = new Chat();
n.name = "chat room";
n.save(function(err,room) {
   console.log(room.id);
});

$ node test.js
4e3444818cde747f02000001
$

I'm on mongoose 1.7.2 and this works just fine, just ran it again to be sure.

Solution 2 - node.js

Mongo sends the complete document as a callbackobject so you can simply get it from there only.

for example

n.save(function(err,room){
  var newRoomId = room._id;
  });

Solution 3 - node.js

You can manually generate the _id then you don't have to worry about pulling it back out later.

var mongoose = require('mongoose');
var myId = mongoose.Types.ObjectId();

// then set it manually when you create your object

_id: myId

// then use the variable wherever

Solution 4 - node.js

You can get the object id in Mongoose right after creating a new object instance without having to save it to the database.

I'm using this code work in mongoose 4. You can try it in other versions.

var n = new Chat();
var _id = n._id;

or

n.save((function (_id) {
  return function () {
    console.log(_id);
    // your save callback code in here
  };
})(n._id));

Solution 5 - node.js

Other answers have mentioned adding a callback, I prefer to use .then()

n.name = "chat room";
n.save()
.then(chatRoom => console.log(chatRoom._id));

example from the docs:.

var gnr = new Band({
  name: "Guns N' Roses",
  members: ['Axl', 'Slash']
});

var promise = gnr.save();
assert.ok(promise instanceof Promise);

promise.then(function (doc) {
  assert.equal(doc.name, "Guns N' Roses");
});

Solution 6 - node.js

Well, I have this:

TryThisSchema.post("save", function(next) {
    console.log(this._id);
});

Notice the "post" in the first line. With my version of Mongoose, I have no trouble getting the _id value after the data is saved.

Solution 7 - node.js

With save all you just need to do is:

n.save((err, room) => {
  if (err) return `Error occurred while saving ${err}`;

  const { _id } = room;
  console.log(`New room id: ${_id}`);
  
  return room;
});

Just in case someone is wondering how to get the same result using create:

const array = [{ type: 'jelly bean' }, { type: 'snickers' }];

Candy.create(array, (err, candies) => {
  if (err) // ...

  const [jellybean, snickers] = candies;
  const jellybeadId = jellybean._id;
  const snickersId = snickers._id;
  // ...
});

Check out the official doc

Solution 8 - node.js

Actually the ID should already be there when instantiating the object

var n = new Chat();
console.log(n._id) // => 4e7819d26f29f407b0... -> ID is already allocated

Check this answer here: https://stackoverflow.com/a/7480248/318380

Solution 9 - node.js

As per Mongoose v5.x documentation:

> The save() method returns a promise. If save() succeeds, the > promise resolves to the document that was saved.

Using that, something like this will also work:

let id;
    
n.save().then(savedDoc => {
    id = savedDoc.id;
});

Solution 10 - node.js

using async function

router.post('/create-new-chat', async (req, res) => {
const chat = new Chat({ name : 'chat room' });
try {
    await chat.save();
    console.log(chat._id);
 }catch (e) {
    console.log(e)
 }
});

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionTIMEXView Question on Stackoverflow
Solution 1 - node.jsRichard HollandView Answer on Stackoverflow
Solution 2 - node.jsAnathema.ImbuedView Answer on Stackoverflow
Solution 3 - node.jsGlennView Answer on Stackoverflow
Solution 4 - node.jsyueView Answer on Stackoverflow
Solution 5 - node.jsJulian OrinyolView Answer on Stackoverflow
Solution 6 - node.jsRoddy P. CarbonellView Answer on Stackoverflow
Solution 7 - node.jsrotimi-bestView Answer on Stackoverflow
Solution 8 - node.jsjazkatView Answer on Stackoverflow
Solution 9 - node.jsKyle MarimonView Answer on Stackoverflow
Solution 10 - node.jsAli MohammadView Answer on Stackoverflow