How can I set a DBref using the referenced document itself and still have access to the document as if it were populated on the parent object?
If I have a simple schema with a field setup as a dbref field:
var PostSchema = new Schema({
'title': String,
'_author', { type: Schema.ObjectId, ref: 'users'}
});
var Post = mongoose.model('posts', PostSchema);
var UserSchema = new Schema({
'name': String
});
Var User = mongoose.model('users', UserSchema);
If I try to do this:
var john = User.findOne({'name': 'john'});
var post = new Post({'title': 'My Post'});
post._author = john;
post.save(function(err) {
if (!err) {
console.log(post._author);
}
});
The post._author property has a value of the author._id. I'd prefer to have the _author property have the value of the entire author document (similar to if I had performed a find query on the posts collection and populated the author object).
My only solution is to perform such a findOne query inside the save callback and ensure that I populate the author back in... this feels a bit off as I'm basically having to requery when I already have all the information.
Any suggestions? Thanks
This is the purpose of the populate functionality of Mongoose. In your example, you'd set post._author = john._id
when creating the post, and then when querying the post collection you'd use code like this to populate _author with the full User object:
post.findOne({'title': 'My Post'}).populate('_author').run(function (err, post) {
// post._author contains a User model instance
});