我正在尝试使用beforeCreate
检查模型中是否存在记录/api/models/User.js
beforeCreate: function (values, cb) {
User.findOne(values.email).exec(function findOneCB(err,found){
console.log('We found '+found.name);
});
},
我得到了
TypeError: Object #<Object> has no method 'findOne'
有没有办法避免从控制器那样做?
答案 0 :(得分:2)
您可以将电子邮件的验证设置为唯一。
module.exports = {
attributes: {
email: {
type: "email",
required: true,
unique: true
},
name: {
type: "string",
required: true
}
},
};
或者如果您想在beforeCreate中执行此操作,则需要正确提供匹配条件。见:
module.exports = {
attributes: {
email: {
type: "email",
required: true
},
name: {
type: "string",
required: true
}
},
beforeCreate: function (values, cb) {
User.findOne({'email': values.email})
.exec(function (err,found){
if(found){
console.log('We found '+found.name);
cb({"error": "duplicate entry"});
}
else{
cb(err, found);
}
});
},
};
答案 1 :(得分:2)
使用
解决sails.models['user']
而不是用户