开发者

Save session as BSON instead of a String on node.js with MongoDB

I am using node.js with express and connect-mongo as session store. When I am开发者_StackOverflow 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?


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.


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.


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
  }
}))
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜