Wednesday, 30 October 2019

How can I increment many fields at once when data structure matches Model exactly in Mongoose?

I currently have a schema with many fields, all of type number like this:

const mySchema = new mongoose.Schema({
    fields: {
        field1: {
            type: Number,
            default: 0
        },
        field2: {
            type: Number,
            default: 0
        },
        ...
        field20: {
            type: Number,
            default: 0
        }
    }
});

const MyModel = mongoose.model('model', mySchema);
module.exports = MyModel;

I currently increment all the fields individually:

const fields = {
    field1: 5,
    field2: 10,
    ...
    field20: 7
};

MyModel.findOneAndUpdate(
    {...},
    {
        $inc: {
            "fields.field1": fields.field1,
            "fields.field2": fields.field2,
            ...
            "fields.field20": fields.field20
        }
    }
);

Is there a shorthand way to increment all these fields at once? Something like below:

MyModel.findOneAndUpdate(
    {...},
    {
        $inc: {
            "fields": fields
        }
    }
);

This understandably gives the error

"Cannot increment with non-numeric argument: ..."



from How can I increment many fields at once when data structure matches Model exactly in Mongoose?

No comments:

Post a Comment