我如何处理风帆中的独特字段? [英] How do I handle a Unique Field in sails?

查看:23
本文介绍了我如何处理风帆中的独特字段?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在我的模型中定义了一个唯一的字段,但是当我尝试测试时,它似乎没有被sails 检查,因为我收到一个 Error (E_UNKNOWN) :: 遇到意外错误:MongoError:E11000 重复键错误索引: 改为sails ValidationError.

I've defined a unique field in my model but when I tried to test it seems like it's not being checked by sails because I get a Error (E_UNKNOWN) :: Encountered an unexpected error: MongoError: E11000 duplicate key error index: instead a sails ValidationError.

处理风帆中独特领域的最佳方法是什么?

What is the best way to handle a unique field in sails?

// model/User.js
module.exports{
attributes: {
  email: {required: true, unique: true, type: 'email' },
  ....
}
// in my controller
User.create({email: 'hello@gmail.com'}).then(...).fail(....)
User.create({email: 'hello@gmail.com'}).then(...).fail(// throws the mongo error ) 
// and same goes with update it throws error

提前谢谢各位.

推荐答案

unique 属性当前 仅在 MongoDB 中创建唯一索引.

您可以使用 beforeValidate() 回调来检查具有该属性的现有记录并将结果保存在类变量中.

You may use the beforeValidate() callback to check for an existing record with that attribute and save the result in a class variable.

这种方法可确保您的模型返回正确的验证错误,客户端可以对其进行评估.

This approach makes sure that your model returns a proper validation error which can be evaluated by clients.

var uniqueEmail = false;

module.exports = {


    /**
     * Custom validation types
     */
    types: {
        uniqueEmail: function(value) {
            return uniqueEmail;
        }
    },

    /**
     * Model attributes
     */
    attributes: {
        email: {
            type: 'email',
            required: true,
            unique: true,            // Creates a unique index in MongoDB
            uniqueEmail: true        // Makes sure there is no existing record with this email in MongoDB
        }
    },

    /**
     * Lifecycle Callbacks
     */
    beforeValidate: function(values, cb) {
        User.findOne({email: values.email}).exec(function (err, record) {
            uniqueEmail = !err && !record;
            cb();
        });
    }
}

编辑

正如thinktt 指出的那样,我以前的解决方案中存在一个错误,导致默认的uniqueEmail 值无用,因为它是在模型声明本身中定义的,因此不能在模型代码中引用.我已经相应地编辑了我的答案,谢谢.

As thinktt pointed out, there was an error in my former solution which rendered the default uniqueEmail value useless since it is defined within the model declaration itself and therefore cannot be referenced within the model code. I've edited my answer accordingly, thanks.

这篇关于我如何处理风帆中的独特字段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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