How do I handle a Unique Field in sails?

后端 未结 6 1250
囚心锁ツ
囚心锁ツ 2020-12-29 15:35

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 un

6条回答
  •  滥情空心
    2020-12-29 16:25

    The unique attribute currently only creates a unique index in MongoDB.

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

    EDIT

    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.

提交回复
热议问题