Search code examples
loopbackjsstrongloop

Loopbackjs: Followers and Followees Model (Twitter-like)


I'd like to create a Twitter-like model but can't manage to make it working:

User's model so far:

 {
   "name": "NsUser",
   "base": "User",
 ...
    "relations": {
        "followers": {
          "type": "hasMany",
          "model": "User",
          "through": "Follow",
          "foreignKey": "followerUserId"
        },
        "followees": {
          "type": "hasMany",
          "model": "User",
          "through": "Follow",
          "foreignKey": "followeeUserId"
        }
    }
}

Follow's model so far:

{
  "name": "Follow",
  "base": "PersistedModel",
...
  "relations": {
    "followee": {
      "type": "belongsTo",
      "model": "NsUser",
      "foreignKey": "followeeUserId"
    },
    "follower": {
      "type": "belongsTo",
      "model": "NsUser",
      "foreignKey": "followerUserId"
    }
  }
}

Then I add a relation in the Follow model:

{
    "created": "2016-08-19T09:23:18.175Z",
    "id": "57b6d0068d55e5368538c8f4",
    "followeeUserId": "578f7ad2ba0bfc40d78ef985",
    "followerUserId": "5790bb3172e2738deb7532ee"
  }

But cannot get the result in http://0.0.0.0:3008/api/NsUsers/5790bb3172e2738deb7532ee/followers Here is the crash:

{
  "error": {
    "name": "Error",
    "status": 500,
    "message": "Relation \"user\" is not defined for Follow model",
    "stack": "Error: Relation \"user\" is not defined for Follow model\n    at processIncludeItem ....
  }
}

I dig a little and found there was a problem similar here: https://github.com/strongloop/loopback-datasource-juggler/pull/394

But it seems I need loop-back-datasource-juggler >= 2.18.0 but I run

 npm update loopback-datasource-juggler
 npm -v loopback-datasource-juggler

It tells me: 2.10.1

Maybe it's the only problem (do I really get the latest version??), or maybe it's my Model which is wrong?


Solution

  • You defined relation model wrongly. Follow model has relation to NsUser, but in NsUser, you defined relation to user.

    Please change like this :

    "relations": {
            "followers": {
              "type": "hasMany",
              "model": "NsUser",
              "through": "Follow",
              "foreignKey": "followerUserId"
            },
            "followees": {
              "type": "hasMany",
              "model": "NsUser",
              "through": "Follow",
              "foreignKey": "followeeUserId"
            }
        }