如何处理帆中的独特场?

gin*_*nad 6 node.js sails.js waterline

我已经在我的模型中定义了一个独特的字段,但是当我尝试测试时,它似乎没有被风帆检查,因为我得到的是Error (E_UNKNOWN) :: Encountered an unexpected error: MongoError: E11000 duplicate key error index:一个风帆ValidationError.

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

// 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
Run Code Online (Sandbox Code Playgroud)

先谢谢你们.

tvo*_*edt 10

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

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

此方法可确保您的模型返回适当的验证错误,客户可以对此进行评估.

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();
        });
    }
}
Run Code Online (Sandbox Code Playgroud)

编辑

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


Chr*_*lan 5

在将电子邮件定义为唯一字段后,您尝试使用相同的电子邮件地址创建两个用户.

也许您可以通过该电子邮件地址查询用户 - 如果已存在 - 返回错误或更新该用户.

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

  });

});
Run Code Online (Sandbox Code Playgroud)

Sails.js和MongoDB:重复键错误索引

在Sails.js文档中还有一些关于独特模型属性的有趣内容 https://github.com/balderdashy/waterline#indexing

编辑:从http://sailsjs.org/#!documentation/models拉出

可用的验证包括:

空,必需,notEmpty,undefined,字符串,alpha,数字,字母数字,电子邮件,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,最长长度