Josh Liptzin Josh Liptzin - 3 months ago 20
Node.js Question

Sails.js model saved to session loses custom instance methods?

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

Answer

When you store things in the session it will run JSON.stringify(values) which will strip functions out of an object.

Comments