Skip to content

document.prototype.$set does not allow merging of subdocuments #8201

@m-weeks

Description

@m-weeks

Do you want to request a feature or report a bug?
Bug

What is the current behavior?
Calling .set on the parent model with the merge option set to true, does not merge subdocuments.

If the current behavior is a bug, please provide the steps to reproduce.
Sample Schema:

var AddressSchema = new mongoose.Schema(
  {
    street: { type: String, required: true },
    city: { type: String, required: true },
    country: { type: String, required: true },
  }
);

var PersonSchema = new mongoose.Schema(
  {
    name: { type: String, required: true },
    address: { Type: AddressSchema, required: true },
  }
);

var Person = mongoose.model('Person', PersonSchema);

With a Person already stored as:

{
  _id: '5d8d2525c1631200550cea41',
  name: 'John Bastion',
  address: {
    _id: '5d7f9ab3f1a6120607784451',
    street: 'Real Street',
    city: 'Vancouver',
    country: 'Canada',
  }
}

And if I call something like the following:

// person is a document
person.set({ name: 'John Bastien', address: { street: 'Fake Street' } }, undefined, { merge: true });
await person.save();

Address is set to simply { street: 'Fake Street' } and is not merged.
It might be worth noting too that person.address.isNew is still false however

What is the expected behavior?
The person object should be updated to:

{
  _id: '5d8d2525c1631200550cea41',
  name: 'John Bastien',
  address: {
    _id: '5d7f9ab3f1a6120607784451',
    street: 'Fake Street',
    city: 'Vancouver',
    country: 'Canada',
  }
}

What are the versions of Node.js, Mongoose and MongoDB you are using? Note that "latest" is not a version.
Mongoose: 5.7.1
Mongodb: 4.0.6

Metadata

Metadata

Assignees

No one assigned

    Labels

    confirmed-bugWe've confirmed this is a bug in Mongoose and will fix it.

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions