Sergei Basharov
Sergei Basharov

Reputation: 53850

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?

Upvotes: 0

Views: 221

Answers (1)

F3L1X79
F3L1X79

Reputation: 2675

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

Upvotes: 1

Related Questions