1
votes

How in Loopback I can extend model with custom function in mixin?

I have:

common/models/user.json

{
  "name": "user",
  "base": "User",
  "idInjection": true,
  "mixins": {
    "ModelRest": {}
  },
  ...
}

common/mixins/model-rest.js

module.exports = function (Model) {


  Model.hello = function() {
    console.log('hello!');
  };
 ...

}

But in common/models/user.js

module.exports = function (User) {

  User.hello();
  ...
}

I've got error:

TypeError: User.hello is not a function

What I'm doing wrong? Thanks for any help.

2
On your user model, you have to use user in lower case. Here have an example: github.com/strongloop/loopback-example-mixins - jrltt
I don't want to use function for instance, I want to use it for model. - Dmytro

2 Answers

1
votes

Mixins added to model after model setup. You call hello in setup phase.

The correct one is :

module.exports = function (User) {

  User.SomeMethod = function(){
    User.hello();
  }             
      ...
}
0
votes

two ways to access methods of other models :

  1. base model : in your case set base model of user as model-rest.

  2. User.app.models.ModelRest.hello();