Stev_k
Stev_k

Reputation: 2126

Loopback related model property problems

I have a user model (extending from built in User) and a UserDetail model which are related:

user relations:

    "relations": {
        "userDetails": {
            "type": "hasOne",
            "model": "UserDetail",
            "foreignKey": "userDetailUserId"
        },

If I run the code below in node, I can see the userDetails property on the returned object, but cannot access it directly.

var User = app.models.user;
User.findOne({
      include: 'userDetails',
      where: {id: userId}
},function(err,user){
  console.log('log');
  console.log(user);
  console.log(user.userDetails);
  console.log(user.userDetailFirstName);
  console.log(user.userDetails.userDetailFirstName);
})

The log is as follows:

log

{ my user details ....
id: 100,
userDetails:
   { userDetailId: 13,
   userDetailUserId: 100,
   userDetailFirstName: 'Stephen',
   userDetailLastName: 'Knox',} }
{ [Function]
   getAsync: [Function],
   create: [Function],
   build: [Function],
   update: [Function],
   destroy: [Function],
   _targetClass: 'UserDetail' }

undefined
undefined

Rather than giving me the userDetails object, which I can see, I get the hasOne methods. This seems odd behaviour but I can't find anything wrong with the model or relationship definition.

Can anyone help?

Upvotes: 2

Views: 422

Answers (2)

Madi Anas
Madi Anas

Reputation: 66

I was pulling my hair trying to understand why am I not getting a related object. Experimenting with .toJSON() fixed it.

Upvotes: 0

Horia Radu
Horia Radu

Reputation: 81

I believe that in order to access a related model, you need to call user.userDetails().

Or, you can call user.toJSON() and this will give you a plain JS object

Upvotes: 1

Related Questions