【问题标题】:Loopbackjs: Cannot cancel a hook (ie: beforeSave)Loopbackjs:无法取消挂钩(即:beforeSave)
【发布时间】:2015-12-11 18:43:53
【问题描述】:

实际上,我正在尝试通过服务器端检查取消挂钩以避免重复的实体名称/子名称对。

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

这是我目前在我的 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();
    });
};

实际上错误已正确显示,实体仍在创建中,我希望它不会是这种情况。

【问题讨论】:

  • 在模型定义文件中创建唯一索引更容易还是使用验证器docs.strongloop.com/display/public/LB/Validating+model+data 更容易?
  • 哈哈,你说得对,但我真正的问题是检查一对(名称+子名)的唯一性......我会更新我的问题......跨度>
  • 在这种情况下,您可以在模型上使用复合索引。 Thomas 就如何防止保存操作给了你一个很好的答案,但我的观点是你可以摆脱不必要的代码。您可以像这样定义复合索引 "indexes": { "name_subname_index": { "keys": { "name": 1, "subname": 1 }, "options": { "unique": true } } } This无需额外代码即可防止重复值。

标签: loopbackjs strongloop


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 2018-06-29
    • 1970-01-01
    • 1970-01-01
    • 2022-10-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多