Search code examples
javascriptsails.jswaterline

Stripped Attributes with toJSON/toObject


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...


Solution

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

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