On my User model I have a custom instance method, getEarnings()
which just adds some other fields in the document together. I'm trying to call this method and display it from my view template as follows, using the user object that's been previously saved to the session after logging in:
<div>
Your earnings are <%= req.session.user.getEarnings() %>
</div>
This doesn't work, sails tells me getEarnings doesn't exist on that object. But if I retrieve the user object from the controller (using User.findOne(...)) and then pass that object into the view parameters, I can do the following
<div>
Your earnings are <%= user.getEarnings() %>
</div>
and it works! Why does the User model lose this custom method when saving it to the session (is it being serialized?)
Please note this example is contrived and I am brand new to sails, I am really just wondering the answer to this specific question (ie. I know I can just set req.session.user.earnings from the controller which would fix this specific problem).
When you store things in the session it will run
JSON.stringify(values)
which will strip functions out of an object.As @particlebanana has said, when you store your User model in req.session.user, you only have it during THIS request. After that, User model is saved in req.session.user, but in JSON format. That means that you have lost all the magic of having a model "object" with "attributes" and "methods". In next request, you'll have only the "attributes" of User model in json format.
Furthermore, if have overwritten toJSON() default method in User model, only that attributes returned by your new toJSON method will be available.
If you'd like to have a User model in every request with the purpose of using the functions declared inside, it is neccesary to retrieve from database the model itself using the id stored in req.session.user.id.