Inside app.js from express.js
just after
var express = require('express');
add
var session = require('express-session');
const mongoose = require('mongoose');
const MongoStore = require('connect-mongo')(session);
mongoose.connect('mongodb://localhost/sessionstore', {
});
mongoose.Promise = global.Promise;
const db = mongoose.connection
then at first app.use add
app.use(session({
secret: 'my-secret',
resave: false,
saveUninitialized: true,
store: new MongoStore({ mongooseConnection: db })
}));
inside some route try to save session
req.session.city = 'Mumbai';
req.session.username = 'sangram';
inside another route try to retreive saved value
console.log(req.session.city)
console.log(req.session.username)
to check data is saved in mongo ,connect to mongo and switch database and check
> show collections
sessions
> db.sessions.find().pretty()
{
"_id" : "yAuqRI1gIxFOHUbxpxjGasiK61ZvrWT-",
"session" : "{\"cookie\":{\"originalMaxAge\":null,\"expires\":null,\"httpOnly\":true,\"path\":\"/\"},\"city\":\"Mumbai\",\"username\":\"sagar\"}",
"expires" : ISODate("2018-10-14T05:32:38.869Z")
}
Code of article can be viewed at https://github.com/gitsangramdesai/mongo-sessionstore-express
No comments:
Post a Comment