【发布时间】: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