无法让猫鼬唯一验证器工作 [英] Cant get mongoose-unique-validator to work

查看:83
本文介绍了无法让猫鼬唯一验证器工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

没那么难,但我总是收到默认的猫鼬 11000 错误.

it cant be that difficult, but I'm always getting the default mongoose 11000 error.

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

Here is a simplified version of my code:

模型

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);

控制器

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)重启节点服务器
4)在邮递员中测试,你会看到比现在更有效

You dont need it.
Actually, unique option for validation working,how?
Follow these steps:
1)set unique: true for certain field in schema(example "email")
2)drop whole db
3)restart node server
4)test in postman and you will see than now works

干杯.

这篇关于无法让猫鼬唯一验证器工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆