【问题标题】:Cant get mongoose-unique-validator to work无法让 mongoose-unique-validator 工作
【发布时间】:2017-08-26 02:10:04
【问题描述】:

不可能那么难,但我总是收到默认的 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'
        }
    }
}

【问题讨论】:

    标签: javascript node.js mongodb validation mongoose


    【解决方案1】:

    你不需要它。
    实际上,验证工作的独特选项,如何?
    请按以下步骤操作:
    1) 设置唯一性:对于架构中的某些字段为 true(例如“电子邮件”)
    2) 删除整个数据库
    3)重启节点服务器
    4)在邮递员中测试,你会看到比现在更有效

    干杯。

    【讨论】:

    猜你喜欢
    • 2022-10-18
    • 2013-05-07
    • 1970-01-01
    • 1970-01-01
    • 2021-08-23
    • 1970-01-01
    • 2013-11-26
    • 2018-04-26
    • 2021-06-15
    相关资源
    最近更新 更多