实际上,我试图取消一个钩子,以避免重复对实体-名称/子名称-通过服务器端检查。
我的例子是,如果已经存在具有相同名称和子名称的实体,我希望它不被创建/保存。
到目前为止,这是我的entity.js中的代码
module.exports = function (ContactType) {
ContactType.observe('before save', function filterSameEntities(ctx, next) {
if (ctx.instance) {
ContactType.find({where: {name: ctx.instance.name, subname: crx.instance.subname}}, function (err, ct) {
if (ct.length > 0) {
//I'd like to exit and not create/persist the entity.
next(new Error("There's already an entity with this name and subname"));
}
});
}
next();
});
};实际上,错误是正确显示的,但是实体仍然是创建的,我希望不是这样的。
发布于 2015-12-11 10:43:53
您的最后一个next();语句总是被调用,因此保存操作总是会发生。
您可以使用return结束进一步的执行。请记住,.find()是异步的,所以只在回调中添加return仍然会导致最后一个next();语句运行。
请试试这个:
module.exports = function (ContactType) {
ContactType.observe('before save', function filterSameEntities(ctx, next) {
if (!ctx.instance) {
return next();
}
ContactType.find({where: {name: ctx.instance.name, subname: ctx.instance.subname}}, function (err, ct) {
if (err) { // something went wrong with our find
return next(err);
}
if (ct.length > 0) {
//I'd like to exit and not create/persist the entity.
return next(new Error("There's already an entity with this name and subname"));
}
return next();
});
});
};https://stackoverflow.com/questions/34204710
复制相似问题