它不可能那么困难,但我总是得到默认的 Mongoose 11000 错误。
这是我的代码的简化版本:model
import mongoose from 'mongoose';
import uniqueValidator from 'mongoose-unique-validator';
const UserSchema = new mongoose.Schema({
email: {
type: String,
index: true,
trim: true,
unique: true,
uniqueCaseInsensitive: true,
required: true
}
});
UserSchema.plugin(uniqueValidator);
controller
var data = {email: 'info@foobar.com'};
var user = new User(data);
user.save(function (err) {
console.log(err);
});
但后来我总是得到这个
{
"code": 11000,
"index": 0,
"errmsg": "E11000 duplicate key error collection: portfolio:27017.users index: email_1 dup key: { : \"info@foobar.com\" }",
"op": {
"email": "info@foobar.com",
"_id": "58de95892be2a000d27ee3bc",
"__v": 0
}
}
而不是这样的
{
message: 'Validation failed',
name: 'ValidationError',
errors: {
username: {
message: 'Error, expected `username` to be unique. Value: `JohnSmith`',
name: 'ValidatorError',
kind: 'mongoose-unique-validator',
path: 'username',
value: 'JohnSmith'
}
}
}
最佳答案
你不需要它。
实际上,验证工作的独特选择,如何?
按着这些次序:
1)设置唯一:对于架构中的某些字段为真(例如“电子邮件”)
2)删除整个数据库
3)重启 Node 服务器
4)在 postman 中测试,你会看到比现在更有效
干杯。
关于javascript - 无法让 mongoose-unique-validator 工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43146862/