在mongodb和nodejs中为模式违规定制validation消息
我的模式如下:
var mongoose = require('mongoose'); var Schema = mongoose.Schema; var StudentSchema = new Schema({ name: { type: String, required: [true, 'name must be non empty'] }, family: { type: String, required: [true, 'family must be non empty'] }, subjects: { type: [String], validate: [{ validator: function(val) { return val.length > 0; }, msg: 'Continents must have more than or equal to one elements', errorCode: 25 } ] }, created: { type: Date, default: Date.now }, });
但是当我发布没有名字的JSON时,我看到下面的错误对象:
{ [ValidationError: Validation failed] message: 'Validation failed', name: 'ValidationError', errors: { name: { [ValidatorError: Validator "required" failed for path name with value `undefined`] message: 'Validator "required" failed for path name with value `undefined`', name: 'ValidatorError', path: 'name', type: 'required', value: undefined } } }
所以,上面的回应有问题:
- '名字必须是非空的'不会到达任何地方
- 价值是未定义的
有没有办法来改变message: 'Validator "required" failed for path name with value
未定义'
? 什么是正确的方法?
问题是我正在使用老版本mongoose。 更新后,它工作正常。 更新到4.5.3版本