首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Loopbackjs:无法取消钩子(即: beforeSave)

Loopbackjs:无法取消钩子(即: beforeSave)
EN

Stack Overflow用户
提问于 2015-12-10 14:41:20
回答 1查看 588关注 0票数 2

实际上,我试图取消一个钩子,以避免重复对实体-名称/子名称-通过服务器端检查。

我的例子是,如果已经存在具有相同名称和子名称的实体,我希望它不被创建/保存。

到目前为止,这是我的entity.js中的代码

代码语言:javascript
复制
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();
    });
};

实际上,错误是正确显示的,但是实体仍然是创建的,我希望不是这样的。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2015-12-11 10:43:53

您的最后一个next();语句总是被调用,因此保存操作总是会发生。

您可以使用return结束进一步的执行。请记住,.find()是异步的,所以只在回调中添加return仍然会导致最后一个next();语句运行。

请试试这个:

代码语言:javascript
复制
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();
        });
    });
};
票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/34204710

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档