mongoose icon indicating copy to clipboard operation
mongoose copied to clipboard

SchemaType Map set always marking as modified

Open fsfarah opened this issue 6 years ago • 0 comments

Bug/Clarification

const MyModel = new Schema({
    myMap: {
        type: Map,
        of: anotherSchema,
        default: {}
    }
});

const anotherSchema = new Schema({
    x: { type: Number }
})

// create instance
const aModel = new MyModel();
aModel.myMap.set('foo', { x: 1 });
aModel.myMap.set('bar', { x: 2 });
// modifiedPaths myMap foo and bar
// save
// retrieve from db
aModel.myMap.set('foo', { x: 1 });
aModel.myMap.set('bar', { x: 2 });
// modifiedPaths are also foo and bar!
// even though the values did not really change

I can solve this manually by comparing the object to be set to an existing one I would like to do this via set method in myMap SchemaType for example:

    myMap: {
        type: Map,
        of: anotherSchema,
        default: {},
        set: function(k, v) {
            if (!this.get(k).deepEqual(v)) {
                this.set(k, v);
            }
        }
    }

How can I achieve that? How can I retrieve the value before it is being set?

MongoDB 3.2 Node.js 10.18 Mongoose ^5.9.3

Regards, Thanks

fsfarah avatar Mar 09 '20 14:03 fsfarah