枚举猫鼬模型自定义错误消息
问题描述:
我想自定义猫鼬模型生成的验证消息。
I would like to customize the validation messages that my Mongoose Models produce.
我倾向于不直接将验证(例如必需)放在模式对象上,因为在那里没有自定义错误消息的自由。
例如
I tend to NOT put my validations (e.g. required) on the schema object directly because there is no freedom to have custom error messages. e.g.
sourceAccountId: {
type: Schema.ObjectId,
require: true,
ref: 'Account'
}
我将执行以下操作。 / p>
instead I do the following.
sourceAccountId: {
type: Schema.ObjectId,
ref: 'Account'
}
ConnectionRequestSchema.path('sourceAccountId').required(true, 'Source Account is required.');
当字段具有枚举约束时,我无法找到一种方法来覆盖默认的枚举消息。
I have been unable to find a way to override the default enum message when a field has enum constraints.
下面列出了我的模型,状态验证消息可以很好地用于必需项,但不能用于枚举。
My Model is Listed Below, with the status validation message working fine for required, but not for 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);
答
尝试类似的事情:
var enu = {
values: ['pending', 'accept', 'decline']
, message: 'Status is required.'
}
var ConnectionRequestSchema = new Schema({
...
status: {
type: String
, enum: enu
, trim: true
}
});