How do I handle a Unique Field in sails?

后端 未结 6 1223
囚心锁ツ
囚心锁ツ 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:26

    The solutions by @tvollstaedt and David posted work but there is a big issue with this code. I was struggling with it all day so I am putting up this slightly modified answer. I would just comment but I do not have the points yet. I will gladly remove this answer if they can update theirs but I would really like to help someone who was having the same issues I've been having.

    The problem with the above code, using the custom validator, is you cannot access the attribute "uniqueEmail" from the properties the way in witch both the previous solutions are trying to do. The only reason it is working in those solutions is because they are inadvertently throwing "uniqueEmail" into the global space.

    The following is a slight modification of the tvollstaedt code that does not use the global space. It defines uniqueEmail outside the modual.exports therefore being scoped only to the module but accessible throughout the module.

    There may yet be a better solution but this is the best I could come up with with minimal changing of an otherwise elegant solution.

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

提交回复
热议问题