Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mongoose populate after save

I cannot manually or automatically populate the creator field on a newly saved object ... the only way I can find is to re-query for the objects I already have which I would hate to do.

This is the setup:

var userSchema = new mongoose.Schema({      name: String, }); var User = db.model('User', userSchema);  var bookSchema = new mongoose.Schema({   _creator: { type: mongoose.Schema.Types.ObjectId, ref: 'User' },   description: String, }); var Book = db.model('Book', bookSchema); 

This is where I am pulling my hair

var user = new User(); user.save(function(err) {     var book = new Book({         _creator: user,     });     book.save(function(err){         console.log(book._creator); // is just an object id         book._creator = user; // still only attaches the object id due to Mongoose magic         console.log(book._creator); // Again: is just an object id         // I really want book._creator to be a user without having to go back to the db ... any suggestions?     }); }); 

EDIT: latest mongoose fixed this issue and added populate functionality, see the new accepted answer.

like image 427
Pykler Avatar asked Nov 23 '12 08:11

Pykler


People also ask

How do I populate after save?

To populate after save with Mongoose, we can use the populate and execPopulate method after calling save . to call t. save to save t in the database. Then we call t.

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.

How does populate work in Mongoose?

Mongoose Populate() Method. In MongoDB, Population is the process of replacing the specified path in the document of one collection with the actual document from the other collection.

Does Mongoose save overwrite?

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


2 Answers

You should be able to use the Model's populate function to do this: http://mongoosejs.com/docs/api.html#model_Model.populate In the save handler for book, instead of:

book._creator = user; 

you'd do something like:

Book.populate(book, {path:"_creator"}, function(err, book) { ... }); 

Probably too late an answer to help you, but I was stuck on this recently, and it might be useful for others.

like image 179
user1417684 Avatar answered Oct 02 '22 10:10

user1417684


The solution for me was to use execPopulate, like so

const t = new MyModel(value) return t.save().then(t => t.populate('my-path').execPopulate()) 
like image 26
François Romain Avatar answered Oct 02 '22 10:10

François Romain