How do I handle a Unique Field in sails?

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

    You are trying to create two users with the same email address after defining the email as a unique field.

    Maybe you can query for a user by that email address - if it exists already - return an error or update that user.

    var params = {email: 'email@email.com'};
    
    User.findOne(params).done(function(error, user) {
    
      // DB error
      if (error) {
        return res.send(error, 500);
      }
    
      // Users exists
      if (user && user.length) {
    
        // Return validation error here
        return res.send({error: 'User with that email already exists'}, 403.9);
      }
    
      // User doesnt exist with that email
      User.create(params).done(function(error, user) {
    
        // DB error
        if (error) {
          return res.send(error, 500);
        }
    
        // New user creation was successful
        return res.json(user);
    
      });
    
    });
    

    Sails.js & MongoDB: duplicate key error index

    There is also an interesting bit about unique model properties in the Sails.js docs https://github.com/balderdashy/waterline#indexing

    EDIT: Pulled from http://sailsjs.org/#!documentation/models

    Available validations are:

    empty, required, notEmpty, undefined, string, alpha, numeric, alphanumeric, email, url, urlish, ip, ipv4, ipv6, creditcard, uuid, uuidv3, uuidv4, int, integer, number, finite, decimal, float, falsey, truthy, null, notNull, boolean, array, date, hexadecimal, hexColor, lowercase, uppercase, after, before, is, regex, not, notRegex, equals, contains, notContains, len, in, notIn, max, min, minLength, maxLength

提交回复
热议问题