First of all, it does not help.
Say we have a User model:
const schema = new mongoose.Schema({ active: { type: Boolean }, avatar: { type: String } }); const User = mongoose.model('User', schema);
When we update it (set the avatar):
We want to check it based on the current (or changed) value of the active attribute.
Case No. 1
active false- we should not be able to set an avatar - it should not pass verification
Case No. 2
active true- we must be able to set an avatar - it must pass the test
Ideas
const schema = new mongoose.Schema({ active: { type: Boolean }, avatar: { type: String, validate: [validateAvatar, 'User is not active'] } }); function validateAvatar (value) { console.log(value);
So this will not work, since we do not have access to the active field.
- Use pre "validate" hook
schema.pre('validate', function (next) {
This method does not work with the update method.
- Use pre "update" hook
schema.pre('update', function (next) { console.log(this.active);
This will not work for us, as it does not have access to the model fields.
- Use Update Error Message
schema.post('update', function (next) { console.log(this.active);
This works, but from the point of view of verification, it is not a good choice, since the function is called only when the model has already been saved.
Question
So, is there a way to check the model based on several fields (both stored in the database and new) before saving them using the model.update() method?
As a summary:
{ active: false, avatar: null }
- Update
User.update({ _id: id }, { $set: { avatar: 'user1.png' } });
- Validation must have access to
{ active: false, avatar: 'user1.png' }
- If validation fails, changes should not be submitted to DB