Mongoose 唯一验证错误类型 [英] Mongoose unique validation error type

查看:23
本文介绍了Mongoose 唯一验证错误类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我将此架构与来自 npm 的 mongoose 3.0.3 一起使用:

I'm using this schema with mongoose 3.0.3 from npm:

var schema = new Schema({

    _id: Schema.ObjectId,
    email: {type: String, required: true, unique: true}

});

如果我尝试保存已经在数据库中的电子邮件,我希望得到一个 ValidationError,就像省略了 required 字段一样.然而事实并非如此,我得到一个 MongoError: E11000 重复键错误索引.

If I try to save a email that is already in db, I expect to get a ValidationError like if a required field is omitted. However this is not the case, I get a MongoError: E11000 duplicate key error index.

这不是验证错误(即使我删除了 unique:true 也会发生).

Which is not a validation error (happens even if I remove the unique:true).

知道为什么吗?

推荐答案

我更喜欢把它放在路径验证机制中,比如

I prefer putting it in path validation mechanisms, like

UserSchema.path('email').validate(function(value, done) {
    this.model('User').count({ email: value }, function(err, count) {
        if (err) {
            return done(err);
        } 
        // If `count` is greater than zero, "invalidate"
        done(!count);
    });
}, 'Email already exists');

然后它会被包裹到 ValidationError 中,并在您调用 validatesave 时作为第一个参数返回.

Then it'll just get wrapped into ValidationError and will return as first argument when you call validate or save .

这篇关于Mongoose 唯一验证错误类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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