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 }
});
我想用更友好的东西来定制它,但我不知道如何为所需的唯一索引和枚举失败设置自定义错误消息。我该怎么办?
答案 0 :(得分:2)
我认为您不能使用所需选项覆盖错误消息。如果您需要在架构中自定义消息,而不是在保存时,我认为您最好的选择是编写自定义验证器,如下所示:
function createdValidator(created) {
return (created !== undefined && created !== null);
}
....
new Schema({created: { type: Date, default: Date.now, validate: [createdValidator, "custom error message"] } });
<强>更新强>
根据文档here,您可以进行多种验证:
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 }});