LearnBoost/mongoose — Issue #570: Mixing populated query results with model objects
Author: DaBlick
Created: 2011-10-20 23:01:48+00:00
State: open

I have a Schema sorta like this (abbreviated here):

var Comment = module.exports = new Schema({
, teacher : { type: Schema.ObjectId, index: true, ref: 'User'}

var StudentProfile = module.exports = new Schema({
, comments : [Comment]

Here's my code to add a new comment. You can presume that std contains the result of a query like

db.model('StudentProfile').findById(id).populate("comment")

And now I execute this code:

var comment = new Comment;
comment.teacher = ~~~ some User object

std.comments.push(comment);

std.save(function (err) {...}

res.render('reporting/_comment', {
'comments' : std.comments,

Assume there is already one Comment and I'm pushing a second one.

Here's what std.comments look likes at the render call

[ {teacher : {User object}},
{teacher : id of User object} } <--- Newly pushed comment

What you can see here is that the pre-existing Comment from the query result is populated, but the new one is not.

With the advent of the populate feature this kind of scenario is not going to be uncommon and it would be quite nice if the model objects the mongoose magic that turns comment.teacher back into an id was transparent.