我有一个项目模型,例如Product
,可以由用户添加。
当用户添加产品时,我希望Loopback在将实体保存到数据库之前添加具有用户ID的字段owner
。
我想我需要看一下.beforeRemote('create', function (context, modelInstance, next) {...})
钩子,但是我看到modelInstance是空的,当我在其中放东西时,它似乎没有通过。
如何在创建项目之前让Loopback添加一些字段?
最佳答案
您在寻找before save
挂钩吗?
module.exports = function (Product) {
Product.observe('before save', function beforeSave(ctx, next) {
if (ctx.instance) {
//on create
ctx.instance.owner = 'yourId';
} else {
// on edit
ctx.data.owner = 'yourId';
}
next();
});
};