我在创建用户对象时使用以下代码来验证用户伪的唯一性。问题是,当我编辑用户对象时,我需要检索当前的user.id.我怎么能这样做?
pseudo: {
type: DataTypes.STRING(150),
allowNull: false,
validate: {
len: {args: [3, 150], msg: "Pseudo shall contains at least 3 characters"},
isUnique: function(value, next) {
User.find({
where: {pseudo: value},
attributes: ['id']
}).done(function(error, user) {
if (error)
return next(error);
if (user)
return next('Pseudo already in use!');
next();
});
}
}
答案 0 :(得分:1)
我是这样做的:
pseudo: {
type: DataTypes.STRING(150),
allowNull: false,
validate: {
len: {args: [3, 150], msg: "Pseudo shall contains at least 3 characters"},
isUnique: function(value, next) {
var id = this.getDataValue('id');
User.find({
where: {pseudo: value},
attributes: ['id']
}).done(function(error, user) {
if (error)
return next(error);
if (user && user.id !== id)
return next('Pseudo already in use!');
next();
});
}
}
},