Mat*_*rds 4 javascript orm node.js sequelize.js
想象一下,我已经定义了以下自定义验证器功能:
isUnique: function () { // This works as expected
throw new Error({error:[{message:'Email address already in use!'}]});
}
Run Code Online (Sandbox Code Playgroud)
但是,当我尝试查询数据库时遇到问题:
isUnique: function (email) { // This doesn't work
var User = seqeulize.import('/path/to/user/model');
User.find({where:{email: email}})
.success(function () { // This gets called
throw new Error({error:[{message:'Email address already in use!'}]}); // But this isn't triggering a validation error.
});
}
Run Code Online (Sandbox Code Playgroud)
如何在自定义验证器中查询ORM并根据ORM的响应触发验证错误?
alv*_*aco 21
您可以验证电子邮件是否已经存在:
email: {
type: Sequelize.STRING,
allowNull: false,
validate: {
isEmail:true
},
unique: {
args: true,
msg: 'Email address already in use!'
}
}
Run Code Online (Sandbox Code Playgroud)
c.h*_*ill 13
以下是功能isUnique验证回调的简化示例(适用于SequelizeJS v2.0.0).我添加了评论来解释重要的一点:
var UserModel = sequelize.define('User', {
id: {
type: Sequelize.INTEGER(11).UNSIGNED,
autoIncrement: true,
primaryKey: true
},
email: {
type: Sequelize.STRING,
validate: {
isUnique: function(value, next) {
UserModel.find({
where: {email: value},
attributes: ['id']
})
.done(function(error, user) {
if (error)
// Some unexpected error occured with the find method.
return next(error);
if (user)
// We found a user with this email address.
// Pass the error to the next method.
return next('Email address already in use!');
// If we got this far, the email address hasn't been used yet.
// Call next with no arguments when validation is successful.
next();
});
}
}
}
});
module.exports = UserModel;
Run Code Online (Sandbox Code Playgroud)
Jon*_*Saw 10
使用Sequelize 2.0,您需要捕获验证错误.
首先,使用自定义验证器定义用户模型:
var User = sequelize.define('User',
{
email: {
type: Sequelize.STRING,
allowNull: false,
unique: true,
validate: {
isUnique: function (value, next) {
var self = this;
User.find({where: {email: value}})
.then(function (user) {
// reject if a different user wants to use the same email
if (user && self.id !== user.id) {
return next('Email already in use!');
}
return next();
})
.catch(function (err) {
return next(err);
});
}
}
},
other_field: Sequelize.STRING
});
module.exports = User;
Run Code Online (Sandbox Code Playgroud)
然后,在控制器中,捕获任何验证错误:
var Sequelize = require('sequelize'),
_ = require('lodash'),
User = require('./path/to/User.model');
exports.create = function (req, res) {
var allowedKeys = ['email', 'other_field'];
var attributes = _.pick(req.body, allowedKeys);
User.create(attributes)
.then(function (user) {
res.json(user);
})
.catch(Sequelize.ValidationError, function (err) {
// respond with validation errors
return res.status(422).send(err.errors);
})
.catch(function (err) {
// every other error
return res.status(400).send({
message: err.message
});
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
19647 次 |
| 最近记录: |