王如锵
王如锵

Reputation: 991

loopback hasMany relation remoteMethod hook

I am using loopback for develop my own website. But recently I had a problem of hasMany remoteMethod. Here is the problem: I have two models :

person.json:

{
  "name": "Person",
  "base": "PersistedModel",
  "strict": true,
  "idInjection": true,
  "properties": {
    /*...
    ....
    */
  },
  "validations": [],
  "relations": {
    "friends": {
      "type": "hasMany",
      "model": "Friend",
      "foreignKey": "personId"
    }
  },
  "acls": [],
  "methods": []
}

friend.json

friend.json:
{
  "name": "friend",
  "base": "PersistedModel",
  "strict": true,
  "idInjection": true,
  "properties": {
    /*...
    ....
    */
  },
  "validations": [],
  "relations": {

  },
  "acls": [],
  "methods": []
}

I want to use beforeRemote when I call POST /api/Persons/{id}/friends.

So I code in person.js

    module.exports = function(Person) {
        Person.beforeRemote('__create__friends', function(ctx, instance, next) {
            /*
                code here
            */
        });
    };

But it does not work!

At the beginning I think it's the matter of '__create__friends',but when I code in person.js like :

    module.exports = function(Person) {
        Person.disableRemoteMethod('__create__friends');
    };

I could disable the '__create__friends' successfully.

So what's the problem?

Can anyone help me?

Upvotes: 3

Views: 1007

Answers (1)

IvanZh
IvanZh

Reputation: 2290

Because methods for related models are attached to Person prototype, you should register hook like this:

Person.beforeRemote('prototype.__create__friends', function() {
    next()
})

Upvotes: 8

Related Questions