且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

我如何处理风帆中的独特字段?

更新时间:2023-11-30 15:52:46

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.