Automattic / mongoose

MongoDB object modeling designed to work in an asynchronous environment.
https://mongoosejs.com
MIT License
26.94k stars 3.84k forks source link

Document set merge doesn't work for multi layer nested documents #14861

Closed ianHeydoc closed 1 month ago

ianHeydoc commented 2 months ago

Prerequisites

Mongoose version

8.6.0

Node.js version

18.15.0

MongoDB server version

NA

Typescript version (if applicable)

No response

Description

When using document set with the merge option set to true if there are multiple nested fields the deeply nested fields are ignored

Steps to Reproduce

const { Schema, model } = require('mongoose');

const personSchema = new Schema({
  info: {
    address: {
      city: String,
      country: { type: String, default: "UK" },
      postcode:String
    },
  }
});

const personModel = model("collection", personSchema);
const document = new personModel({
  info: {
    address: { country: "United States", city: "New York" },
  }
});
console.log(document);

document.$set({ info: { address: { postcode: "12H" } } }, null, { merge: true });

console.log(document);

Expected Behavior

For this code example I get

{
  info: { address: { postcode: '12H', country: 'UK' } },
  _id: new ObjectId('66d693ee34802938adef5702')
}

I would expect to get

{
  info: { address: { city: 'New York', country: 'United States',  postcode: '12H' } },
  _id: new ObjectId('66d692b9c9fe017af8ab4f78')
}
ianHeydoc commented 2 months ago

I've taken a look into the code and found this code snippet

this is on line 1212 of mongoose/lib/document.js

      if (!merge) {
        this.$__setValue(path, null);
        cleanModifiedSubpaths(this, path);
      } else {
        return this.$set(val, path, constructing);
      }

It looks like the merge option is lost when the second nested object is set

I've tested out adding the options to the next $set call and it looks like it works 👀

Would this be something I could open a pr to implement or is there a reason for the behaviour?

I'm new to looking at the source code for mongoose so any help would be appreciated 😃

pdrf commented 2 months ago

+1

vkarpov15 commented 1 month ago

Should be fixed by #14870