我弄的Schema如下,加了一些验证, 另外也试过了UserSchema.path(‘name’).validate(function (name){})但这个验证是之后执行的,错误会被定义Schema时的验证先捕获,然后只给出“validate error",也不给出哪项validate error, 有没有 自定义的验证错误提示信息的方法? var UserSchema = new Schema({ id: ObjectId , name: { type: String, trim: true, required: true } , username: { type: String, trim: true, lowercase: true, required: true, unique: true } , phoneNumber: { type: String, trim: true, required: true , unique: true } , hashed_password: { type: String, trim: true } , tempPasswordFlag: { type: Boolean, default: false } , email: { type: String, trim: true, lowercase: true, required: true, unique: true } , newEmail: { type: String, trim: true, lowercase: true, default: ‘’ } , emailValidatedFlag: { type: Boolean, default: false } , role: { type: String, enum: ['User’, 'Subscriber’, ‘Admin’], default: 'User’, required: true } , update_date: { type: Date, default: Date.now} //Create_date 通过objectId可以得到 id.getTimesstamp() , avatar: { type: String, trim: true } , imageId:{ type: ObjectId } //外键引入图片表内某一项 })
@i5ting 有没有定义验证或者约束的时候同时定义错误提示 的方法? 如: var UserSchema = new Schema({ name: { type: String, trim: true, {required: true,errorMessage:"name is required,please input." }
@iamcc pre save 方法在预定义的验证之后才执行, 比如name: { type: String, trim: true, required: true } ,触发此处required 验证后,pre save里面写 if(this.name&&this.name!=null) 就不会被触发,已经被拦截了,validate()方法也是在其之后执行
var toySchema = new Schema({
color: String,
name: String
});
var Toy = mongoose.model('Toy', toySchema);
Toy.schema.path('color').validate(function (value) {
return /blue|green|white|red|orange|periwinkle/i.test(value);
}, 'Invalid color');
Toy.update({}, { color: 'bacon' }, { runValidators: true }, function (err) {
console.log(err.errors.color.message); // prints 'Validator "Invalid color" failed for path color with value `bacon`'
});
还是自己找到了办法
// custom error messages
// We can also use the special {MAX} token which will be replaced with the invalid value
var max = [Date(‘2014-01-01’), ‘The value of path {PATH}
({VALUE}) exceeds the limit ({MAX}).’];
var schema = new Schema({ d: { type: Date, max: max })
var M = mongoose.model('M’, schema);
var s= new M({ d: Date(‘2014-12-08’) });
s.validate(function (err) {
console.log(String(err)) // ValidationError: The value of path d
(2014-12-08) exceeds the limit (2014-01-01).
})