mongoose.connect giving error in nodejs - node.js

I am using node to connect to mongoose database, but when i run the code, it gives error as:
Uncaught TypeError: undefined is not a function
(anonymous function) server.js:13
Below is the code which i am running in server.js
var express= require(['express']);
var bodyParser = require(['body-parser']);
var cookieParser = require(['cookie-parser']);
var expressSession = require(['express-session']);
var mongoose = require(['mongoose']);
var mongoStore = require(['connect-mongo'])({session: expressSession});
require(['./models/users.js']);
mongoose.connect('mongodb://localhost/userregistration');
var app = express();
app.engine('.html', require('ejs').__express);
app.set('views',__dirname + '/views');
app.set('view engine','html');
app.use(bodyParser());
app.use(cookieParser());
app.use(expressSession({
secret: 'SECRET',
cookie: {maxAge:60*60*1000 },
store: new mongoStore({
db: mongoose.connection.db,
collection: 'sessions'
})
}));
require('./routes')(app);
app.listen(80);
looking at the logs, the code is giving the error at:
mongoose.connect('mongodb://localhost/userregistration');

I think you forgot to require express-session.
Here is the example
ExpressSession
app.use(express.session({
secret: 'SECRET',
cookie: {maxAge:60*60*1000 },
store: new mongoStore({
db: mongoose.connection.db,
collection: 'sessions'
})
}));

connect-mongo has a special option for using Mongoose connections, try using that:
store: new mongoStore({
mongoose_connection: mongoose.connection,
collection: 'sessions'
})
If that doesn't fix it, please post more information (like a full stack trace and the actual code you're running, since those require's don't look right).

// Replace 'db' by 'mongooseConnection '
app.use(expressSession({
secret: 'SECRET',
cookie: {maxAge: 60 * 60 * 1000},
store: new mongoStore({
mongooseConnection: mongoose.connection,
collection: 'sessions'
})
}));

Related

Class constructor MongoStore cannot be invoked without 'new' (Express-NodeJs)Backend

I m creating react-auth . Firstly I created server side. I need to connect mongodb but i didnt manage.
const session = require('express-session') const Mongostore = require('connect-mongo')(session)
``const cors = require('cors')
app.use(session({ secret: 'secret',
store: new Mongostore({ mongooseConnection: mongoose.connection
}), resave: true,
saveUninitialized: true }))
For those who want to the latest version of connect-mongo, the new syntax involves removing the parameter session from the require call and not using new any more but a method .create.
Here is what the documentation recommends:
const session = require('express-session');
const MongoStore = require('connect-mongo');
app.use(session({
secret: 'foo',
store: MongoStore.create(options)
}));
Basic usage would be:
app.use(session({
store: MongoStore.create({ mongoUrl: 'mongodb://localhost/test-app' })
}));
I had a similar issue while working on replit. My solution was to downgrade connect-mongo's version from 4 to 3.
npm uninstall connect-mongo
npm i connect-mongo#3
From this user's post:
https://forum.freecodecamp.org/t/advanced-node-and-express-error/450979/3
const session=require("express-session");
const MongoStore=require("connect-mongo");
//*****************
app.use(session({
secret:"secret",
cookie:{maxAge:60000},
resave:false,
saveUninitialized:false,
store:MongoStore.create({mongoUrl:process.env.MONGO_URI}),
I also had the same Error, What i did was to npm i connect-mongodb-session
const MongoStore = require('connect-mongodb-session)(session)
I then created a middleware by session
app.use(
session({
secret: 'keyboard cat',
resave: false,
saveUninitialized: false,
store: new MongoStore({ mongooseConnection: process.env.MONGO_URI }),
})
);
Instead of coding my URI directly, i instead loaded it from the .env file with process.env.MONGO_URI
Please make the following changes on your code, from:
const MongoStore = require('connect-mongo')(session);
Use, instead:
const MongoStore = require('connect-mongo')
And in the session object options use:
store: MongoStore.create({ mongoUrl: process.env.CONNECTIONSTRING })
process.env.CONNECTIONSTRING is the link provided by mongodb that you may store in the .env
I tried downgrading the mongo-connect version as suggested above but found it more reliable to keep it up to date with current version and using the new method create with different key name, following the documentation guidelines

mongo-connect error with mongo-connect(session)

After searching around about it, I can't find any solution or mistake in my code about this error. I've got my app.js files inside my node JS application with the mongo-connect declaration :
const MongoStore = require('connect-mongo')(session)
And I've got this error :
TypeError: Class constructor MongoStore cannot be invoked without
'new'
at Object. (/Users/souhailmohamed/project/devops/story website/app.js:11:20)
at Module._compile (internal/modules/cjs/loader.js:1063:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1092:10)
at Module.load (internal/modules/cjs/loader.js:928:32)
at Function.Module._load (internal/modules/cjs/loader.js:769:14)
at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:72:12)
at internal/main/run_main_module.js:17:47
There is my app.use code beloww :
app.use(session({
secret: 'story book',
resave: false,
saveUninitialized: false,
store: new MongoStore({ mongooseConnection: mongoose.connection })
}))
I understand pretty well about the
const MongoStore = require('connect-mongo')(session)
but I didn't understand the error. But it's from a tutorial from youtube by traversy media LinK
connect-mongo v4 introduces new signature (compared to v3).
Here is the official migration guide.
Also, here is a quick diff of what I changed in my specific project (using mongoose and dotenv) to upgrade from connect-mongo v3 to v4:
I had the same problem in my code and solved it using this:
const MongoDbStore = require('connect-mongo');
Remove (session) from the require statement and update the app.use() like this:
// Session Config
app.use(
session({
secret: 'story book',
resave: false,
saveUninitialized: false,
store: MongoDbStore.create({
mongoUrl: YourDatabaseURL
})
})
);
I was following the same so I discovered an npm pakage connect-mongodb-session.
Install it and use the same code of session as Brad uses in his video
const MongoDBStore = require('connect-mongodb-session')(session);
//sessions
app.use(session({
secret: 'keyboard cat',
resave: false,
saveUnitialized: false,
store: new MongoDBStore({
mongooseConnection: mongoose.connection
})
//cookie: { secure: true }
}))
const store = new MongoStore({
uri: 'your mongo uri' ,
collection:'mySessions'
})
//express middleware
app.use(session({
secret: 'keyboard cat',
resave: false,
saveUninitialized: false,
store: store
// Don't create a session until something is stored
// cookie: { secure: true } - this wont work without https
}))
It solved my relogging issue also. If you close the tab and renter to localhost you get yourself logged in already
Ok so i've found a way to resolve it, i don't about the reason, on which version of express to use but i removed the (session) after mongo-connect and change the app.use to this :
app.use(session({
secret: 'story book',
resave: false,
saveUninitialized: false,
store: MongoStore.create({ mongoUrl: 'mongodb+srv://<id+ password>#cluster0.cq7f2.mongodb.net/DBname?retryWrites=true&w=majority' })
}))
Certain rule are changed for the syntax in "connect-mongo" document here
const MongoStore = require("connect-mongo");
secret: 'keyboard cat',
resave: false,
saveUninitialized: false,
store: MongoStore.create({
mongoUrl: process.env.MONGO_URI //(URI FROM.env file)
})
//stroed it in database
}));
In your app.js make the following changes:
let MongoStore = require('connect-mongo');
app.use(
session({
secret: 'keyboard cat',
resave: false,
saveUninitialized: false,
store: MongoStore.create({
mongoUrl: 'your mongo url'
})
});
);
References:
https://www.npmjs.com/package/connect-mongo
It seems that 'connect-mongo' is obsolete and the newer version includes 'connect-mongodb-session'
const MongoDBStore = require('connect-mongodb-session')(session);
Use the above code instead and it should work without any errors.
Note: install the 'connect-mongodb-session' package using npm init connect-mongodb-session
I have same problem. Here is the solution:
var session = require('express-session');
var MongoStore = require('connect-mongo');
var mongoose = require('mongoose');
mongoose.Promise = global.Promise;
app.use(session({
secret : 'mysecretkey',
resave : true,
saveUninitialized : true,
store :MongoStore.create({ mongoUrl: DBUrl })
}));
app.use(session({
store: MongoStore.create({ mongoUrl: 'mongodb://localhost/test-app' })
}));
// Advanced usage
app.use(session({
store: MongoStore.create({
mongoUrl: 'mongodb://user12345:foobar#localhost/test-app?authSource=admin&w=1',
mongoOptions: advancedOptions // See below for details
})
}));
Here is the solution:
const session = require('express-session');
const MongoStore = require('connect-mongo');
const mongoose = require('mongoose');
app.use(session({
secret: 'story book',
resave: false,
saveUninitialized: false,
store: new MongoStore({
mongoUrl: mongoose.connection._connectionString,
mongoOptions: {}
})
}))
Just use the another npm package connect-mongodb-session and it should work
https://www.npmjs.com/package/connect-mongodb-session
const MongoDBStore = require('connect-mongodb-session')(session);

Redis not working on express-session

The code below is quite a normally snippet, but it's not working, session from request is undefined. Anyone who can give me a hint will be appreciated.
var express = require('express');
var session = require('express-session');
var redisStore = require('connect-redis')(session);
var app = express();
app.listen(3000);
app.use(session({
store: new redisStore({
host:'localhost',
port:'8543'
}),
resave: false,
saveUninitialized: true,
secret: 'somesecrettoken'
}));
app.get('/', function (req, res) {
if(req.session.isVisit) {
req.session.isVisit++;
res.send('<p>times to be here:' + req.session.isVisit + '</p>');
} else {
req.session.isVisit = 1;
res.send('1st time to be here');
}
});
A Redis client is required
var redis = require("redis"); // You can use any module to create redis client
app.use(session({
store: new redisStore({
client : redis.createClient(<your setting>)
host:'localhost',
port:'8543'
}),
resave: false,
saveUninitialized: true,
secret: 'somesecrettoken'
}));
Please refer this link:
https://www.npmjs.com/package/connect-redis
Pass the express-session store into connect-redis to create a RedisStore constructor.
var session = require('express-session');
var RedisStore = require('connect-redis')(session);
app.use(session({
store: new RedisStore(options),
secret: 'keyboard cat'
}));

req.user undefined in Express 4

I built an app that uses Oauth to authenticate with a third party Jawbone app. I'm attempting to pull req.user.jawbone.token from req.user in one of my routes; however, I'm getting an error stating that req.user is undefined. I had this working in express 3, but after upgrading to express 4 it's no longer working - which leads me to believe that my sessions aren't being stored properly.
Here are the relevant parts of my app.js configuration:
var passport = require('passport');
var session = require('express-session')
var MongoStore = require('connect-mongo')({session: session});
require('./config/passport')(passport);
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
// passport
app.use(passport.initialize());
app.use(passport.session()); // persistent login sessions
app.use(session({
store: new MongoStore({
url: mongoUrl
}),
secret: 'password',
resave: false,
saveUninitialized: true
}));
For anyone else that runs into this problem, the issue was due to my middleware being in the wrong order. I rearranged to the below and it's working properly
app.use(session({
store: new MongoStore({
url: mongoUrl
}),
secret: 'password',
resave: false,
saveUninitialized: true
}));
app.use(passport.initialize());
app.use(passport.session());

How are connect-mongo MongoStore sessions actually saved?

I implemented sessions using Passport, but for storing sessions I tried connect-mongo using a mongoose connection.
This is my code (sessions part):
var express = require('express')
var mongodb = require('mongodb')
var mongoose = require('mongoose')
var bodyParser = require('body-parser')
var cookie = require('cookie-parser')
var connect = require('connect')
var passport = require('passport')
//var flash = require('connect-flash')
var session = require('express-session');
var MongoStore = require('connect-mongo')(session);
var LocalStrategy = require('passport-local').Strategy;
var app = express()
var BSON = mongodb.BSONPure
app.use(express.static(__dirname+"/public"))
app.use(bodyParser())
app.use(cookie())
app.use(connect.session({ secret: 'ilovescotchscotchyscotchscotch' }));
app.use(passport.initialize());
app.use(passport.session());
mongoose.connect('mongodb://localhost/psicologosTuxtepecDB')
var Schema = mongoose.Schema
var userCredential = new Schema({
username: String,
password: String
}, {
collection: 'members'
})
var userCredentials = mongoose.model('members', userCredential)
app.use(session({
secret: 'ziKologiia',
clear_interval: 900,
cookie: { maxAge: 2 * 60 * 60 * 1000 },
store: new MongoStore({
db : mongoose.connection.db
})
}));
Something I doubt if it would be counterproductive is that app.use(connect.session({ secret: 'ilovescotchscotchyscotchscotch' })) is usingconnect module but the MongoStore configuration is set upon a express-session variable. However, deleting first causes app to not work good (won't authenticate/redirect).
So, about my question title. Where is that session stored? I really thought I could go to my Mongo database and find any collection storing it.
How can I find such sessions at backend (Mongo) and even at the applicacion as Java Script objects?
connect-mongo stores sessions in the "sessions" collection by default. They should be there and visible in the mongo shell or any GUI tool like robomongo. Yes, it is created by default. I would pass in the mongooose_connection option instead of db.
From the docs:
mongoose_connection in the form: someMongooseDb.connections[0] to use an existing mongoose connection. (optional)
One thing you should do is replace
app.use(connect.session({ secret: 'ilovescotchscotchyscotchscotch' }));
with your
app.use(session({
secret: 'ziKologiia',
clear_interval: 900,
cookie: { maxAge: 2 * 60 * 60 * 1000 },
store: new MongoStore({
db: mongoose.connection.db
});
}));
Updated Method of MongoClient:
import session from "express-session";
import MongoStore from "connect-mongo";
app.use(
session({
secret: "Your Key",
cookie: {
maxAge: 60000 * 60 * 24, //1Sec * 1H * 24 = 1 Day
secure: process.env.NODE_ENV !== "production"? false : true
},
resave: true,
saveUninitialized: true,
store: MongoStore.create({ mongoUrl: process.env.MongoDBUrl}),
})
);

Resources