枚举猫鼬模型自定义错误消息 [英] Mongoose Model Custom Error Message for Enums

查看:73
本文介绍了枚举猫鼬模型自定义错误消息的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想自定义猫鼬模型生成的验证消息。

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
  }
});

这篇关于枚举猫鼬模型自定义错误消息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆