How to use ValidatedMethod for update/upsert?

upsertDoc = new ValidatedMethod({
    name: 'Doc.methods.upsert',
    validate: Schema.Doc.validator(),
    run(newDoc) {
 ...
    }
});

When pass an object with object with a modifier ($set: {…}) I got the error:

When the validation object contains mongo operators, you must set the modifier option to true

Of course I could write my own validation method but I’m wondering if there is another way to do this.

I haven’t tested, but according to the docs, it should be something like this. It is a SimpleSchema issue by the way, unrelated to ValidatedMethod itself.

upsertDoc = new ValidatedMethod({
    name: 'Doc.methods.upsert',
    validate: Schema.Doc.validator({
      modifier: true
    }),
    run(newDoc) {
      // ...
    }
});

I’ve also tried Schema.Doc.validator({modifier: true}); but without success. According the Change Log it is implemented since 1.5.0.

This is because the validator function doesn’t pass the modifier flag to the real validate function.

use new Schema like this one:

new ValidatedMethod({
    name: 'Posts.methods.update',
    validate: new SimpleSchema({
        _id: {
            type: String
        },
        modifier: {
            type: Object,
            blackbox: true
        }
    }).validator(),

Like so the modifier is not really validated on the method call but it will be verified when performing the update thanks to the collection2 package (which I suppose you have installed).

2 Likes

OK thank you, I got the change log description wrong. I think it would be helpful if you can pass validation options to the validator.

One thing: With this solution I also have to do the client side validation by myself. Maybe it would be better to do something like this:

new ValidatedMethod({
    name: 'Posts.methods.update',
    validate(doc) {Schema.Doc.validate(doc, options);},
...