node.js - Any way for Mongoose to continue save if validation fails for some changes? -
in schema i've set minimum length requirements keys.
mphone: {type: string, minlength: 1}, hphone: {type: string, minlength: 1}, wphone: {type: string, minlength: 1},
the information above populated through form user submits. when user submits form, following runs save information db.
var query = sample.where({'sample.email' : username}); query.findone(function(err, sample) { if(err) { console.error(err); } else { sample.mphone = req.body.mphone; sample.hphone = req.body.hphone; sample.wphone = req.body.wphone; sample.save(function(err) { if(err) console.error(err); }); }
however, if user fills out 1 of fields in form , submits (for instance, fill out mphone), because of validation on schema, whole save operation rejected. there setting allow mongoose reject invalid fields , save, say, mphone? guess test , save each 1 individually, i'd know if there more efficient way.
some operations (e.g. create()) skip validation altogether according docs.
that said, if rule @ least 1 of fields filled out, should use validation middleware. (untested):
sampleschema.pre('validate', function(next){ if(!this.mphone && !this.hphone && !this.wphone) return next(new validationerror('at least 1 type of phone needed!')); next(); });
Comments
Post a Comment