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

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?

127794 次浏览

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.

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;
});

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));

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

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

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.

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");
});

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

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;
});

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)
}
});