Mongoose 怎么弄自定义的 验证错误message?
发布于 1个月前 作者 pangguoming 206 次浏览 来自 问答

我弄的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 } //外键引入图片表内某一项 })

10 回复

在操作db之前就已经校验完了。。。。so,不存在

@i5ting 有没有定义验证或者约束的时候同时定义错误提示 的方法? 如: var UserSchema = new Schema({ name: { type: String, trim: true, {required: true,errorMessage:"name is required,please input." }

@pangguoming 这个是表单该做的事儿。。。。

@i5ting 我做的是个纯REST API服务端,必须在服务端验证的。

@pangguoming 用is模块,校验参数

我是在pre save 里面做校验,自定义错误信息。

@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`'
});

@yujingz 想要自定义 validate message , 恐怕只能像你这么做了,把定schema时的验证统统去掉,然后改成用validate()方法统一处理

还是自己找到了办法 // 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). })

回到顶部