我想自定义Mongoose Models产生的验证消息。
我倾向于不直接在架构对象上放置我的验证(例如必需),因为没有自由拥有自定义错误消息。 e.g。
sourceAccountId: {
type: Schema.ObjectId,
require: true,
ref: 'Account'
}
而是执行以下操作。
sourceAccountId: {
type: Schema.ObjectId,
ref: 'Account'
}
ConnectionRequestSchema.path('sourceAccountId').required(true, 'Source Account is required.');
当字段具有枚举约束时,我无法找到覆盖默认枚举消息的方法。
我的模型列在下面,状态验证消息适用于所需,但不适用于枚举。
'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);
答案 0 :(得分:12)
尝试类似的东西:
var enu = {
values: ['pending', 'accept', 'decline']
, message: 'Status is required.'
}
var ConnectionRequestSchema = new Schema({
...
status: {
type: String
, enum: enu
, trim: true
}
});
答案 1 :(得分:0)
难度:{ 类型:字符串, 必填:[是的,“游览必有困难。”], 枚举:{ 值:['easy','medium','difficult'], 信息:“困难要么容易,要么中等,要么困难”。 } }
答案 2 :(得分:0)
const tourSchema = new mongoose.Schema(
{
difficulty: {
type: String,
required: [true, 'A tour must have a difficulty'],
enum: {
// works only for string
values: ['easy', 'medium', 'difficult'],
message: 'Difficulty level is either: easy, medium, or difficult',
},
}
}
);