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?
4 Answers
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.
-
I think this is a node.js specific problem, as i thought the mongodb-connect session handler would already manage it like that.– ThomasCommented Apr 20, 2011 at 20:40
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.
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.
-
This does not really answer the question. If you have a different question, you can ask it by clicking Ask Question. To get notified when this question gets new answers, you can follow this question. Once you have enough reputation, you can also add a bounty to draw more attention to this question. - From Review– LasithdsCommented Jun 3, 2022 at 8:25
Add stringify: true in you session DB setup:
//We register the expressSession middleware in our express_server_router
express_server_router.use(expressSession({
//Pass in the configuration object with value secret
//The secret string is used to sign and encrypt the session ID cookie being shared with the browser
secret: ENV.express_session_secret,
resave: false,
saveUninitialized: true,
store: MongoStore.create({
// mongoUrl: 'mongodb+srv',
mongoUrl: ENV.database_link,
// mongoUrl: 'mongodb+srv',
collectionName: 'sessions',
// ttl: 1000*60*60*24 // 1 Day,
stringify: true,
}),
cookie: {
secure: false,
sameSite: 'strict',
//originalMaxAge: 24*60*60
maxAge: 1000*60*60*24 // 1 Day
}
}))
"JSON object"
has really taken off. It may become one of those misnomers likeXMLHttpRequest
which has nothing to do with XML.