Loopbackjs:无法取消挂钩(即:beforeSave)

Loopbackjs: Cannot cancel a hook (ie: beforeSave)

实际上我正在尝试取消挂钩以避免重复对 entity-name/subname - 通过服务器端检查。

我的示例是,如果已经存在具有相同名称和子名称的实体,我希望它不是 created/persisted。

到目前为止,这是我的代码 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();
    });
};

实际上错误显示正确,但是实体仍在创建中,我希望情况并非如此。

您最后的 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();
        });
    });
};