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

和自甴很熟 提交于 2019-12-12 04:57:53

问题


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


回答1:


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




回答2:


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.



来源:https://stackoverflow.com/questions/24297489/sails-js-model-saved-to-session-loses-custom-instance-methods

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!