目的:
创建用于验证的自定义消息
我尝试的内容
我的架构:
var locationSchema = new mongoose.Schema({
locationId: { type: String, required: true,index:true },
stockingLocationId: { type: String, required: true,index:true},
parentStockingLocationId: { type: String },
stockingLocationDescription: { type: String },
created: { type: Date, default: Date.now },
lastModified: { type: Date, default: Date.now },
isActive: { type: Boolean , default : true },
isDeleted: { type: Boolean , default : false }
});
locationSchema.index({locationId:1, stockingLocationId:1}, { unique: true });
我想为后一行的uniquess验证抛出自定义消息。
locationSchema.index({locationId:1, stockingLocationId:1}, { unique: true });
答案 0 :(得分:0)
您可以尝试 mongoose-unique-validator 包,为Mongoose架构中的唯一字段添加预保存验证,并且还可以更轻松地处理错误,因为当您收到Mongoose验证错误时您尝试违反唯一约束,而不是来自MongoDB的E11000错误:
var mongoose = require('mongoose');
var uniqueValidator = require('mongoose-unique-validator');
var locationSchema = new mongoose.Schema({
locationId: { type: String, required: true,index:true },
stockingLocationId: { type: String, required: true,index:true},
parentStockingLocationId: { type: String },
stockingLocationDescription: { type: String },
created: { type: Date, default: Date.now },
lastModified: { type: Date, default: Date.now },
isActive: { type: Boolean , default : true },
isDeleted: { type: Boolean , default : false }
});
locationSchema.index({locationId:1, stockingLocationId:1}, { unique: true });
locationSchema.plugin(uniqueValidator, { message: 'Error, expected {PATH} to be unique.' });