不能得到mongoose独特validation工作

它不是那么困难,但我总是得到默认mongoose11000错误。

这里是我的代码的简化版本:

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' } } } 

       

网上收集的解决方案 "不能得到mongoose独特validation工作"