mongoose icon indicating copy to clipboard operation
mongoose copied to clipboard

populated returning incorrect value after doc.save()

Open newmanw opened this issue 11 years ago • 4 comments

I have the following schemas:

var FooSchema = new Schema({
  barId: { type: Schema.Types.ObjectId, ref: 'Bar', required: true },
});
var BarSchema = new Schema({
...
});

If I grab a doc by and populate barId:

  Foo.findById(id).populate('barId').exec(function(err, foo) {
    callback(err, foo);
  });

Then later I update that foo document's barId

  foo.barId = 12345;
  Foo.save(function(err, foo) {
    callback(err, foo);
  });

At that point barId is no longer populated on the foo object. However if I ask if the barId is populated I get an id back.

Should mongoose handle the situation in which I populate the barId, then set the barId to something and expect the populated method to return the right thing?

newmanw avatar Aug 25 '15 22:08 newmanw

What do you mean by "set the barId to something and expect the populated method to return the right thing?"?

vkarpov15 avatar Aug 26 '15 16:08 vkarpov15

After I populate barId the foo object will look something like this:

{
  barId: {
     something: 'yup',
     other: 'hello'
  }
}

However if I want to assign a new barId to foo and save:

foo.barId = 12345;
foo.save(....);

That foo object now looks like this:

{
  barId: 12345
}

But if I call:

var barId = foo.populated('barId);
// barId is set to '12345; meaning barId has been populated.  But that is no longer true.

Since barId is no longer populated I would expect this method to return null.

newmanw avatar Aug 26 '15 16:08 newmanw

That looks like a bug. Thanks :)

vkarpov15 avatar Aug 26 '15 18:08 vkarpov15

Please don't send messages to me.

qzhongyou avatar Aug 27 '15 12:08 qzhongyou