Search code examples
node.jsmongoosemongoose-schema

Mongoose schema setter not being called when using $inc


I'm facing an issue with the set function in my Mongoose schema sometimes not being triggered when using the $inc operator with a negative value in an update query.

I have a Mongoose schema with a setter function defined for a field that should format its value before it is saved to the database. The schema looks like this:

const userSchema = new mongoose.Schema({
    money: {
        balance: {
            type: Number,
            set: (v) => Number(v)?.toFixed(4),
            default: 0,
        },
    },
});

However, when I update the field using the $inc operator in a findByIdAndUpdate query with a negative value, the set function is not called, and the value is not formatted:

await User.findByIdAndUpdate(userId, {
        $inc: {
            'money.balance': -1.3245479576,
        },
    },
    { runValidators: true }
);

Solution

  • The issue I was encountering with Mongoose has been fixed in this commit on GitHub: https://github.com/Automattic/mongoose/issues/13158