2016-11-04 85 views
0

我有一個項目模型,說Product,它可以由用戶添加。如何在Loopback中創建Model實例時以編程方式填充字段?

當用戶添加產品時,我希望Loopback在將實體保存到數據庫之前添加字段owner和用戶標識。

我想我需要看看.beforeRemote('create', function (context, modelInstance, next) {...})掛鉤,但我看到modelInstance是空的,當我把東西放入它時,它似乎並沒有通過。

如何讓Loopback在創建項目前添加一些字段?

回答

1

您是否在尋找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(); 
      }); 
}; 
+0

使用操作掛鉤而不是遠程掛鉤。 http://loopback.io/doc/en/lb2/Operation-hooks.html –