Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 595
TIMEX Avatar asked Jul 28 '11 05:07

TIMEX


People also ask

What does save () return in Mongoose?

The save() method is asynchronous, and according to the docs, it returns undefined if used with callback or a Promise otherwise.

What is ObjectId in Mongoose?

ObjectId . A SchemaType is just a configuration object for Mongoose. An instance of the mongoose. ObjectId SchemaType doesn't actually create MongoDB ObjectIds, it is just a configuration for a path in a schema.

Does Mongoose save overwrite?

Mongoose save with an existing document will not override the same object reference. Bookmark this question.

Does Mongoose auto generate ID?

_id field is auto generated by Mongoose and gets attached to the Model, and at the time of saving/inserting the document into MongoDB, MongoDB will use that unique _id field which was generated by Mongoose.


1 Answers

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.

like image 115
Richard Holland Avatar answered Sep 24 '22 00:09

Richard Holland