0
var userSchema = Schema({
  email: {
    type: String,
    unique: true,
    match: /^[a-z0-9._-]+@[a-z0-9.-]+\.[a-z]{2,4}$/,
    lowercase: true,
    trim: true
  },
  nickname: {
    type: String,
    trim: true,
    required: true
  },
  password: { type: String, required: true },
  url: { type: String, trim: true, default: '' },
  role: {
    type: String,
    enum: [ 'admin', 'reader' ],
    default: 'reader'
  },
  about: { type: String, trim: true },
  created: { type: Date, default: Date.now, required: true }
});

我想用更用户友好的东西来定制它,但我不知道如何为所需的唯一索引和枚举失败设置自定义错误消息。我能怎么做?

4

1 回答 1

2

我认为您不能使用所需选项覆盖错误消息。如果您需要在模式中自定义消息,而不是在保存时,我认为您最好的选择是编写自定义验证器,如下所示:

function createdValidator(created) {
  return (created !== undefined && created !== null);
}

....

new Schema({created: { type: Date, default: Date.now, validate: [createdValidator, "custom error message"] } });

更新:

根据此处的文档,您可以进行多个验证,如下所示:

var multiple = [
  { validator: createdValidator, msg: "custom error message" },
  { validator: function(created){ return true;}, msg: "You'll never see me" }
];

new Schema({created: { type: Date, validate: multiple }});
于 2013-01-04T18:23:53.117 回答