我想自定义Mongoose模型生成的验证消息。
我倾向于不直接对模式对象进行验证(例如,required),因为没有自定义错误消息的自由。
sourceAccountId: {
type: Schema.ObjectId,
require: true,
ref: 'Account'
}
而是执行以下操作。
sourceAccountId: {
type: Schema.ObjectId,
ref: 'Account'
}
ConnectionRequestSchema.path('sourceAccountId').required(true, 'Source Account is required.');
当字段具有枚举约束时,我无法找到覆盖默认枚举消息的方法。
下面列出了我的模型,状态验证消息对required正常工作,但对enum不正常。
'use strict';
var _ = require('lodash');
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var ConnectionRequestSchema = new Schema({
created_at: { type: Date },
updated_at: { type: Date },
sourceAccountId: {
type: Schema.ObjectId,
ref: 'Account'
},
status: {
type: String,
enum: ['pending', 'accept', 'decline'],
trim: true
}
});
// ------------------------------------------------------------
// Validations
// ------------------------------------------------------------
ConnectionRequestSchema.path('sourceAccountId').required(true, 'Source Account is required.');
ConnectionRequestSchema.path('status').required(true, 'Status is required.');
//ConnectionRequestSchema.path('status').enum(['pending', 'accept', 'decline'], 'Status is invalid, valid values include [pending, accept, decline]');
// ------------------------------------------------------------
// Save
// ------------------------------------------------------------
ConnectionRequestSchema.pre('save', function (next) {
var now = new Date().getTime();
this.updated_at = now;
if (!this.created_at) {
this.created_at = now;
}
next();
});
module.exports = mongoose.model('ConnectionRequest', ConnectionRequestSchema);
6条答案
按热度按时间vuktfyat1#
尝试类似的方式:
pgccezyw2#
ohtdti5x3#
这应该可行:
zsbz8rwp4#
svujldwt5#
Because you should write like that . Error is type value.
will be fixed.
1rhkuytd6#
你也可以这么做