使用 MongoDB 将会话保存为 BSON,而不是 Node.js 上的字符串
我使用带有express和connect-mongo的node.js作为会话存储。当我在 mongo 中检查会话集合时,每个数据集中只有 _id 属性和会话属性。会话属性的值是一个字符串。有没有办法将会话数据存储为 BSON?
I am using node.js with express and connect-mongo as session store. When I am checking my sessions collection in mongo, there is only the _id attribute a session attribute in each dataset. The value of the session attribute is a String. Is there any way to store the session data as BSON?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
也许我不直接理解你的问题,但 MongoDB 已经使用 BSON 存储所有内容。因此,如果您按原样存储 Session 集合,它也会被转换为 JSON 字符串。
参考: http://www.mongodb.org/display/DOCS/Inserting
<强>编辑:
也看看这个> Mongo JSON 文档 -> JSON-> BSON
这可能对您的特定场景有所帮助。
Maybe I don't understand your question directly but MongoDB already stores everything using BSON. So if you even store it your Session collection as it is, it will get converted into a JSON string.
reference: http://www.mongodb.org/display/DOCS/Inserting
EDIT:
Also take a look at this > Mongo JSON document -> JSON -> BSON
This may help in your specific scenario.
这就是这个特定中间件的编写工作方式(尽管谁知道为什么这样做)。
当将会话对象保存到 mongodb 时,它会将其转换为 json 字符串,并在再次读取时将其转换回对象。
如果您希望将会话对象存储为相同的对象,我建议切换到替代 connect-mongodb 中间件mongodb。 connect-mongodb 的连接与 connect-mongo 有点不同,但是一旦设置了连接,API 的其余部分是相同的,因此您现有的代码应该可以正常工作。
That is simply the way this particular middleware was written to work (though who knows why it was done that way).
It converts your session object into a json string when it saves it to mongodb, and converts it back into an object when it's read again.
I suggest switching to the alternative connect-mongodb middleware if you want session objects stored as the same object in mongodb. The connection for connect-mongodb is a bit different from connect-mongo, but once you have the connection set up, the rest of the api is the same so your existing code should just work.
好问题,我自己也在努力解决这个问题。我唯一能想到的就是将其保留为字符串 json。然后,如果您需要查询属性,请循环访问会话集合并检查特定的正则表达式,该正则表达式针对您正在查找的属性。
good question, I'm struggling with this myself. The only thing I can think of is to keep it as string jsons. Then if you need to query for a property, loop through the session collections and check for a particular regex, that targets the property you are looking for.
在会话数据库设置中添加 stringify: true :
Add stringify: true in you session DB setup: