Josh Liptzin Josh Liptzin - 2 years ago 171
Node.js Question

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

On my User model I have a custom instance method,

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:

Your earnings are <%= req.session.user.getEarnings() %>

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

Your earnings are <%= user.getEarnings() %>

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 Source

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download