简体   繁体   中英

How to populate a field programmatically when a Model instance is created in Loopback?

I have an item model, say Product , which can be added by a User.

When user adds a product, I want Loopback to add a field owner with user id before saving the entity to the DB.

I suppose I need to have a look into .beforeRemote('create', function (context, modelInstance, next) {...}) hook but I see that modelInstance is empty and when I put something into it, it doesn't seem to go through.

How do I make Loopback add some field before creating an item?

Were you looking for the before save hook?

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();
            });
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM