简体   繁体   中英

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?

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM