98
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?

TIMEX
  • 259,804
  • 351
  • 777
  • 1,080

9 Answers9

126

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.

Richard Holland
  • 2,663
  • 2
  • 21
  • 35
  • 9
    an undefined room object is indicative of an error saving n. its best practice to perform an error check before accessing the document. – ChrisMcJava Jan 11 '15 at 06:42
  • 5
    both n._id and n.id will return the desired result as of mongoose 3.8.21 – ChrisMcJava Jan 11 '15 at 06:56
  • @ChrisMcJava your comment was a life saver! When we code many lines and many functions, sometimes we left the error handling later, later could be never or forgotten LOL, Thanks anw! – ksugiarto Aug 06 '15 at 07:05
  • Someone did write the answer more succinctly on a later date but I think the extra bit in this answer may be more helpful. For that I give this one the up-vote (8 years down the line, no less). – Cheesus Toast Mar 19 '19 at 00:49
49

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;
  });
Anathema.Imbued
  • 3,271
  • 4
  • 17
  • 18
17

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
Glenn
  • 4,195
  • 9
  • 33
  • 41
  • Very helpful to know, prevented asynchronous code when synchronous would do. Thanks! – ryanm Jan 10 '18 at 17:27
  • That was what I was originally going to do but I think it is unnecessary to be honest. Would answer a different question though. – Cheesus Toast Mar 19 '19 at 00:45
12

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));
Mike
  • 23,542
  • 14
  • 76
  • 87
yue
  • 121
  • 1
  • 5
4

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");
});
Julian Orinyol
  • 576
  • 5
  • 4
2

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.

Roddy P. Carbonell
  • 858
  • 1
  • 11
  • 16
2

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

jazkat
  • 5,600
  • 3
  • 25
  • 17
2

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;
});
Kyle Marimon
  • 606
  • 6
  • 11
1

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

rotimi-best
  • 1,852
  • 18
  • 29