3

I am trying to run validation on my schema before updating and here's the code for it.

Schema

var workSchema = mongoose.Schema({
location: {
    type: String,
    required: true,
    enum: LOCATIONS
},
flags: {
    isHourly: {
        type: Boolean,
        default: false,
        validate: [workValidators, 'Message']
    }
}
});


function workValidators(flag) {
 if (flag) {
/* WHY IS .this NUll? */
assert(this.location, 'Must have location specified');
}}



workSchema.findByIdAndUpdate(id, {
   $set: info
}, {
   runValidators: true,
   new: true
 }).then((updatedModel) => {
  return updatedModel.toObject();
});
};
Community
  • 1
  • 1
eugenekgn
  • 1,504
  • 15
  • 36

1 Answers1

1

This is because the THIS in the validation function has a different THIS context. The idea is only to provide a simple validation against the parameter that is being passed. If you want something more complex, try with the mongoose hooks.

Leonardo Venoso
  • 1,105
  • 11
  • 15