保存到会话的 Sails.js 模型丢失自定义实例方法? [英] Sails.js model saved to session loses custom instance methods?

查看:40
本文介绍了保存到会话的 Sails.js 模型丢失自定义实例方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的用户模型上,我有一个自定义实例方法,getEarnings(),它只是将文档中的一些其他字段添加到一起.我正在尝试调用此方法并按如下方式从我的视图模板中显示它,使用登录后先前保存到会话的用户对象:

您的收入是 <%= req.session.user.getEarnings() %>

这不起作用,sails 告诉我该对象上不存在 getEarnings.但是如果我从控制器中检索用户对象(使用 User.findOne(...)),然后将该对象传递给视图参数,我可以执行以下操作

您的收入是 <%= user.getEarnings() %>

它有效!为什么 User 模型在保存到 session 的时候会丢失这个自定义方法(是否被序列化了?)

请注意这个例子是人为的,我是风帆的新手,我真的只是想知道这个特定问题的答案(即.我知道我可以从控制器设置 req.session.user.earnings 这将修复这个特定的问题).

解决方案

当你在 session 中存储东西时,它会运行 JSON.stringify(values) 这将从对象中剥离函数.

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.

这篇关于保存到会话的 Sails.js 模型丢失自定义实例方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆