i am trying to create session with mongodb in node.js
already i have a connection like this
var Db=require('mongodb').Db;
var BSON=require('mongodb').BSONPure;
var Server=require('mongodb').Server;
var client=new Db('db',new Server('localhost', 27017), {safe:false});
and then i have tried to configure session like this
app.use(express.session({
store: new mongoStore({ db: client }),
secret: 'topsecret'
}));
i ran the server.js file i got this error mongoStore undefined
so to resolve this error i have added this
var mongoStore= require('connect-mongodb');
again i ran it i did't get any error but i got below error when i tried to find or save data into db
Cannot call method 'findOne' of undefined
how to resolve this problem and how to create session with mongodb in node.js
Here's a very simple setup:
var express = require('express');
var MongoStore = require('connect-mongo')(express);
var app = express();
app.use(express.cookieParser()); // required to handle session cookies!
app.use(express.session({
secret : 'YOUR_SESSION_SECRET',
cookie : {
maxAge : 10000 // expire the session(-cookie) after 10 seconds
},
store : new MongoStore({
db: 'sessionstore'
// see https://github.com/kcbanner/connect-mongo#options for more options
})
}));
app.get('/', function(req, res) {
var previous = req.session.value || 0;
req.session.value = previous + 1;
res.send('<h1>Previous value: ' + previous + '</h1>');
});
app.listen(3012);
If you run it and open http://localhost:3012/ in your browser, it will increase the value by 1 each time you reload. After 10 seconds, the session will expire and the value will be reset to 0.
Related
I'm working currently with one NodeJS + Express + Mongodb Applicacion and I need to get information stored in another monogodb database. So in my app.js file I'm doing the following steps in my app:
app.js
var session = require('express-session');
var MongoStore = require('connect-mongo')(session);
var mongoose = require('mongoose');
var passport = require('passport');
var configDB = require('./config/database.js');
// here I get the info from the Database IP and port.
mongoose.connect(configDB.url);
app.use( session({store: new MongoStore({mongoose_connection: mongoose.connections[0]}),
secret: 'secretPass',
cookie: {maxAge: 36000}, // session secret
saveUninitialized: true,
resave: true}
));
Is there a way to add another connection so I can use it so get information stored in the second database?
Thanks a Lot!
You can use the following code:
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/database1'); // database connection
mongoose.connect('mongodb://localhost/database2');
I've been having problems trying to access stored session values! Once I've set the values and try access them from a new route, I get undefined! So basically I've got a login (POST) and in that request I set the session data, and then I have a show user details (POST) where I try and access the session data I've just stored.
Setup
// Setup express and needed modules #############################################
var express = require('express'),
session = require('express-session'),
cookieParser = require('cookie-parser'),
redis = require("redis"),
redisStore = require('connect-redis')(session),
bodyParser = require('body-parser');
var client = redis.createClient(), //CREATE REDIS CLIENT
app = express();
// Setup app
app.use(cookieParser('yoursecretcode'));
app.use(session(
{
secret: 'x',
store: new redisStore({
port: 6379,
client: client
}),
saveUninitialized: true, // don't create session until something stored,
resave: false // don't save session if unmodified
}
));
app.use(bodyParser.urlencoded({ extended: true}));
app.use(bodyParser.json());
app.set('trust proxy', 1) // trust first proxy
So as you've seen my setup, you know I'm using express sessions and Redis. Below is where I'm setting the session values! If I print out the session values here it works, but then If I try and access the session data in another route it returns undefined.
Routes
I send a http post request and set the session data:
router.route('/login/').post(function(req, res) {
req.session.userId = req.body.uId;
req.session.name = req.body.uName;
// THIS PRINTS OUT IF I TRY AND ACCESS THE SESSION DATA HERE
console.log("THIS PRINTS OUT --> " + req.session.name);
});
So now that the session values have been set, I can go access them right, no, I get undefined each time I try and log them out.
router.route('/user/printoutuserdetails').post(function(req, res) {
// THESE RETURN UNDEFINED
console.log(req.session.userId);
console.log(req.session.uName);
console.log("THIS PRINTS OUT --> " + req.session.name);
});
Does anyone have any idea what's happening? I've tried everything and looked everywhere and can't seem to find a way to get it to work!
Solved:
The reason this wasn't was because you're not suppose to use sessions when using a RESTFUL api.
I'm new to NodeJS. I am developing a REST API and using express-session to deal with sessions. So, to get the session ID I'm using
var sessionID = req.sessionID
This sessionID is generated from the server side. So, when I scale up to two or more servers, this is a problem. For example, if one server shuts down and the request is redirected to another server (Assuming I have a load balancer), a new session ID is generated. So, is there a way to retrieve the session ID from the client side?
Good question! Session management can be challenging to get up and running with - especially since to get up and running with any sort of sophisticated session management in node you need a ton of different packages, each with their own set of docs. Here is an example of how you can set up session management with MongoDB:
'use strict';
var express = require('express'),
session = require('express-session'),
cookieParser = require('cookie-parser'),
mongoStore = require('connect-mongo')(session),
mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/someDB');
var app = express();
var secret = 'shhh';
app.use(session({
resave: true,
saveUninitialized: true,
secret: secret,
store: new mongoStore({
mongooseConnection: mongoose.connection,
collection: 'sessions' // default
})
}));
// ROUTES, ETC.
var port = 3000;
app.listen(port, function() {
console.log('listening on port ' + port + '.')
});
This configuration gives you access to req.sessionID but now it should persists across app servers if the user's session cookie has not expired.
I hope this works!
I am using connect-mongo to store my session data, blew is the code to start my express server and mongodb session.
var MongoStore = require('connect-mongo')(express);
var sessionStore = new MongoStore({url: config.sessionStore}, function() {
console.log('connect mongodb session success...');
})
app.configure(function(){
............
// // cookieParser should be above session
app.use(express.cookieParser());
// express/mongo session storage //
app.use(express.session({
cookie: { maxAge: 24 * 60 * 60 * 1000 },
store: sessionStore,
secret: config.sessionSecret,
key: 'express.sid',
clear_interval: 3600
}));
............
})
I have looked into the chrome browser and can of course see my session key- 'express.sid' and corresponding value.
when the user logs into my server, I want to get their session data from my mongodb session store. However, session store query the session data with no error but just showing the output null.
var connect = require('express/node_modules/connect')
, parseSignedCookie = connect.utils.parseSignedCookie
, cookie = require('express/node_modules/cookie');
function fileUpload(req, res) {
var sid = req.cookies['express.sid'];
var sessionID = parseSignedCookie(sid, config.sessionSecret);
console.log('fileUpload ',req.ip, sid,sessionID);
// output the session value as expected
// but session store can't query the session data, no error but just no values
sessionStore.get(sid, function(err, session){
// access to session
if(err) console.log("session store err".red,error);
else console.log("sessionStore auth ".green+session);
});
res.send(200);
};
What goes wrong with my node, or any another things I missed?
Using expressjs and connect-mongo
I am unable to access any of the prototyped functions that are set in the connect-mongo.js file (https://github.com/kcbanner/connect-mongo/blob/master/lib/connect-mongo.js)
In my case I am trying to access the 'get' on the MongoStore obj function and getting the lovely error:
has no method 'get'
Here is the code I am using:
Var MongoStore = require('connect-mongo');
///... express code
app.use(express.session({
secret: conf.secret,
maxAge: new Date(Date.now() + 3600000),
store: new MongoStore(conf.db)
}));
//....more express code
MongoStore.get(sessionId, function(err, result){
console.log(result);
});
What do you think would be the issue here? Do I need to create the object in another place maybe for the prototyped functions to be picked up?
Yes, you'd need to create an instance of MongoStore, and call "get" on it. I'd quick fix your code as below:
var MongoStore = require('connect-mongo');
var sessionStore = new MongoStore(conf.db); // <-- you missed this instantiation
///... express code
app.use(express.session({
secret: conf.secret,
maxAge: new Date(Date.now() + 3600000),
store: sessionStore
}));
//....more express code
sessionStore.get(sessionId, function(err, result){
console.log(result);
});