Tuesday, 18 April 2017

$addToSet in Mongoose does not run custom update validation

I would like to use a custom validation when updating a document. Despite being available since version 4.8.0 (according to the docs), the validator does not get called for an update using the $addToSet field. Here is my document schema:

var schema = mongoose.Schema({
    registered: {
        type: [
            {
                type: ObjectId,
                ref: "User"
            }
        ],
        validate: {
            validator: function(v) {
                return (v.length <= this.getUpdate().$set.maxRegistration);
            }
        }
    },
    maxRegistration: {
        type: Number
    }
});
var Blob = mongoose.model("Blob", schema);

Later on I call it as such:

Blob.findOneAndUpdate(
    { name: "blob1" },
    { $addToSet: { playersRegistered: "76741abc983" } },
    { runValidators: true, context: "query" }
).then(...)

but the validator is not called. It is called when a new Blob is created however. I am running Mongoose v4.9.5 so I don't know where the problem is. Thank you for your help!



via Barnab

No comments:

Post a Comment