0

I have something like the following code:

User.findOne(id)
    .exec((err, user) => {
        Pets.find(_.pluck(user.pets, 'id'))
            .populate("toys")
            .exec((err, petsWithToys) => {
                 user.pets = petsWithToys;
                 return res.ok({ user: user });
             });
    });

When I look at the response in the client I don't see the toys array inside the pet.

I thought maybe this was due to overriding the toJSON function in my User model but even when removing it I get the same behavior.

Also, I've found out that if I assign the values to a new property that is not defined in the model, I do see the values at the client. I.e. if I do

user.petsNew = petsWithToys;

I will see the fully populated property.

I've seen the documentation of toObject where is says it removes instance methods (here) but I am not sure why the collection is considered a method and don't understand how after changing the value it is still removed.

Any comments/explanations/workarounds?

P.S. Tried to step through the code but can't step into toObject...

Tomer Cagan
  • 1,078
  • 17
  • 31
  • When you set a breakpoint on the `user.pets = petsWithToys;` line and inspect `user`, does it have `toys`? – T.J. Crowder May 18 '17 at 17:57
  • 1
    What version of Lodash are you using? since v.4 `_.pluck` is being removed in favor of `_.map`. See [this link](http://stackoverflow.com/questions/35136306/what-happened-to-lodash-pluck) – Zuzu Softman May 19 '17 at 04:29
  • @T.J.Crowder - yes, there is - it is only removed in toJSON/toObject call. It seems the suggestion in the answer below would work (need to test). – Tomer Cagan May 21 '17 at 07:26
  • @ZuzuSoftman - I'm using 3.10.x which is bundled with sails.js - thanks for the tip though - I'll look into it. – Tomer Cagan May 21 '17 at 07:26

1 Answers1

1

Add user = user.toJSON(); before user.pets = petsWithToys;

Check https://stackoverflow.com/a/43500017/1435132

Community
  • 1
  • 1
Sangharsh
  • 2,999
  • 2
  • 15
  • 27