Error: Cannot init client | mongo-connect express-session - mongodb

I am getting error while trying to save session on mongodb. Here is my code..
const express = require("express");
const session = require("express-session");
const MongoStore = require("connect-mongo").default;
const app = express();
let sessionOptions = session({
secret: "JavaScript is cool",
store: MongoStore.create({ client: require("./db") }),
resave: false,
saveUninitialized: false,
cookie: { maxAge: 1000 * 60 * 60 * 24, httpOnly: true },
});
app.use(sessionOptions);
const router = require("./router");
app.use(express.urlencoded({ extended: false }));
app.use(express.json());
app.use(express.static("public"));
app.set("views", "views");
app.set("view engine", "ejs");
app.use("/", router);
module.exports = app;
and db.js
const dotenv = require("dotenv");
dotenv.config();
const mongodb = require("mongodb");
mongodb.connect(
process.env.CONNECTIONSTRING,
{ useNewUrlParser: true, useUnifiedTopology: true },
(err, client) => {
module.exports = client;
const app = require("./app");
app.listen(process.env.PORT);
}
);
And the error is here..
Assertion failed: You must provide either mongoUr|clientPromise in options
/home/irfan/Desktop/Brad_Sciff/Complex_App/node_modules/connect-mongo/build/main/lib/MongoStore.js:121
throw new Error('Cannot init client');
^
Error: Cannot init client
at new MongoStore (/home/irfan/Desktop/Brad_Sciff/Complex_App/node_modules/connect-mongo/build/main/lib/MongoStore.js:121:19)
at Function.create (/home/irfan/Desktop/Brad_Sciff/Complex_App/node_modules/connect-mongo/build/main/lib/MongoStore.js:137:16)
at Object.<anonymous> (/home/irfan/Desktop/Brad_Sciff/Complex_App/app.js:9:21)
at Module._compile (internal/modules/cjs/loader.js:778:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:789:10)
at Module.load (internal/modules/cjs/loader.js:653:32)
at tryModuleLoad (internal/modules/cjs/loader.js:593:12)
at Function.Module._load (internal/modules/cjs/loader.js:585:3)
at Module.require (internal/modules/cjs/loader.js:692:17)
at require (internal/modules/cjs/helpers.js:25:18)
I tried to change from const MongoStore = require("connect-mongo").default to const MongoStore = require("connect-mongo")(session)
But the error is showing..
const MongoStore = require("connect-mongo")(session);
^
TypeError: require(...) is not a function
at Object.<anonymous> (/home/irfan/Desktop/Brad_Sciff/Complex_App/app.js:4:44)
at Module._compile (internal/modules/cjs/loader.js:778:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:789:10)
at Module.load (internal/modules/cjs/loader.js:653:32)
at tryModuleLoad (internal/modules/cjs/loader.js:593:12)
at Function.Module._load (internal/modules/cjs/loader.js:585:3)
at Module.require (internal/modules/cjs/loader.js:692:17)
at require (internal/modules/cjs/helpers.js:25:18)
at mongodb.connect (/home/irfan/Desktop/Brad_Sciff/Complex_App/db.js:10:17)
at /home/irfan/Desktop/Brad_Sciff/Complex_App/node_modules/mongodb/lib/utils.js:693:5
Using Connect-mongo 4.2, express-session 1.17.1 express 4.17.1 mongodb 3.6.4
Don't know what I am missing.
Please help.
Thanks in Advance.
Irfan.

So it looks like connect-mongo has been updated recently. I came across this issue today as well and here's how I fixed it.
How it used to be:
const session = require('express-session');
const MongoStore = require('connect-mongo')(session);
app.use(
session({
...options
store: new MongoStore({ mongooseConnection: mongoose.connection }),
})
);
How it is now:
const session = require('express-session');
const MongoStore = require('connect-mongo').default;
app.use(
session({
store: MongoStore.create({ mongoUrl: process.env.MONGO_URI }),
...options
})
);
Try passing your connection string into mongoURL instead of client and see if that helps.
You can read more about connect-mongo in their docs.

the following is worked for me.
const mongoose = require("mongoose");
const session = require("express-session");
const MongoStore = require("connect-mongo");
const url = 'mongodb://localhost/mydb';
mongoose.connect(url, { useNewUrlParser: true, useCreateIndex: true,
useUnifiedTopology: true, useFindAndModify: true });
const connection = mongoose.connection;
connection.once('open', () => {
console.log("database connected successfully...");
}).catch(err => {
console.log("connection failed...");
});
// session store
let store = new MongoStore({
mongoUrl: url,
collection: "sessions"
});
// session config
app.use(session({
secret: process.env.COOKIE_SECRET,
resave: false,
store: store,
saveUninitialized: false,
cookie: { maxAge: 1000 * 60 * 60 * 24 }, // 24 hours
}));

what I did was to downgrade from mongodb version 4 to version 3. Hence, in your terminal, uninstall connect-mongo and reinstall lower version.
"npm uninstall connect-mongo"
"npm i connect-mongo#3"
this allows you to be able to pass in your session to the MongoStore.
"const path = require('path')
const express = require('express')
const mongoose = require ('mongoose')
const dotenv = require('dotenv')
const morgan = require('morgan')
const exphbs = require ('express-handlebars')
const passport = require('passport')
const session = require ('express-session')
const MongoStore = require('connect-mongo')(session)"

This is latest solution
add this lines
First
var session = require('express-session');
var MongoStore = require ('connect-mongo');
Second
app.use(session(
{
secret: '**something** like mysupersecret',
store: MongoStore.create({
mongoUrl: '**your url**like mongodb://localhost/test-app'}),
}));

There is an another npm package connect-mongodb-session,
https://www.npmjs.com/package/connect-mongodb-session
Install it and it should work.
const MongoDBStore = require('connect-mongodb-session')(session);

This worked for me,
const session = require('express-session');
const MongoStore = require('connect-mongo');
const dbUrl = process.env.DB_URL;
app.use(session({
secret: 'thisismysecret',
resave: false,
saveUninitialized: false,
store: MongoStore.create( {
mongoUrl: dbUrl,
touchAfter: 24 * 3600
}) }));

Related

I am getting error that say -> TypeError: Class constructor MongoStore cannot be invoked without 'new'

`Error TypeError: Class constructor MongoStore cannot be invoked without 'new'
** MY code is:**
const url = 'mongodb://localhost/pizza';
mongoose.connect(url, { useNewUrlParser: true, useUnifiedTopology: true });
const connection = mongoose.connection;
mongoose.connection
.once('open', function () {
console.log('Database connected');
})
.on('error', function (err) {
console.log(err);
});
// session
let mongoStore = new MongoDbStore({
mongooseConnection: connection,
collection: 'sessions'
})```
```// session config
app.use(session({
secret: process.env.COOKIE_SECRET,
resave: false,
store: mongoStore,
saveUninitialized: false,
cookie: { maxAge: 1000 * 60 * 60 * 24 } // 24 hour
}))```
`
**This is the error i am getting **`
const MongoDbStore = require('connect-mongo')(session)
^
TypeError: Class constructor MongoStore cannot be invoked without 'new'
at Object. (C:\Projects\pizza\server.js:21:46)
at Module._compile (node:internal/modules/cjs/loader:1126:14)
at Object.Module._extensions..js (node:internal/modules/cjs/loader:1180:10)
at Module.load (node:internal/modules/cjs/loader:1004:32)
at Function.Module._load (node:internal/modules/cjs/loader:839:12)
at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:81:12)
at node:internal/main/run_main_module:17:47
`Please help to solving the error `
`**I tried some solution from thee stackOverflow but still not able to solve the problem**`

Unable to connect to the database when run e2e testing in nestJS with mongodb-memory-server

I run the e2e test using mongodb memory server to mock database, create database successfully but when testBuilderModule is compile, i faced the problem about connection with database:
[Nest] 18908 - 05/26/2022, 2:33:29 PM ERROR [MongooseModule] Unable to connect to the database. Retrying (1)...
Here is the code when we init the app for testing :
const db = await MongoMemoryReplSet.create({
replSet: { count: 1, storageEngine: 'wiredTiger' },
});
const dbUrl = db.getUri();
jest.spyOn(helpers, 'createMongooseOptions').mockImplementation(() => ({
uri: dbUrl,
useNewUrlParser: true,
useCreateIndex: true,
useFindAndModify: false,
useUnifiedTopology: true,
}));
let testBuilder = Test.createTestingModule({
imports: [AppModule],
});
const fixture = await testBuilder.compile();
const app = fixture.createNestApplication();
const logger = {
error: jest.fn(),
};
app.useGlobalPipes(new ValidationPipe());
await app.init();
Here is dev version
"mongodb-memory-server": "^8.4.2",
"#nestjs/testing": "^8.0.0",
"#types/jest": "27.4.1",
"supertest": "^6.1.3",
"jest": "^27.2.5",
"ts-jest": "^27.0.3",
I can not find why it's running into this error because the db and testBuilder were created successfully. Is there a problem about version or something?

I have some problem with my homework to connect to mongodb using mongoose

const mongoose = require("mongoose")
const app = require("../app")
const dotenv = require("dotenv");
dotenv.config();
const PORT = process.env.PORT || 3000
const DB_PATH = process.env.DB_CONNECTION_URL
const db = mongoose
.connect(DB_PATH, {
useCreateIndex: true,
useNewUrlParser: true,
useUnifiedTopology: true,
useFindAndModify: false,
})
.then(() => {
console.log("Database connection successful");
app.listen(PORT, () => {
console.log(`Server running. Use our API on port: ${PORT}`);
});
})
.catch((error) => {
console.log(error);
process.exit(1);
});
module.exports = db
Snapshot
MongooseError: The uri parameter to openUri() must be a string, got "undefined". Make sure the first parameter to mongoose.connect() or mongoose.createConnection() is a string.
at NativeConnection.Connection.openUri (/Volumes/Mac - Data/GitHub/hw7/nodejs-homework2-rest-api/node_modules/mongoose/lib/connection.js:694:11)
at /Volumes/Mac - Data/GitHub/hw7/nodejs-homework2-rest-api/node_modules/mongoose/lib/index.js:351:10
at /Volumes/Mac - Data/GitHub/hw7/nodejs-homework2-rest-api/node_modules/mongoose/lib/helpers/promiseOrCallback.js:32:5
at new Promise ()
at promiseOrCallback (/Volumes/Mac - Data/GitHub/hw7/nodejs-homework2-rest-api/node_modules/mongoose/lib/helpers/promiseOrCallback.js:31:10)
at Mongoose._promiseOrCallback (/Volumes/Mac - Data/GitHub/hw7/nodejs-homework2-rest-api/node_modules/mongoose/lib/index.js:1149:10)
at Mongoose.connect (/Volumes/Mac - Data/GitHub/hw7/nodejs-homework2-rest-api/node_modules/mongoose/lib/index.js:350:20)
at Object. (/Volumes/Mac - Data/GitHub/hw7/nodejs-homework2-rest-api/bin/server.js:11:4)
at Module._compile (internal/modules/cjs/loader.js:1085:14)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1114:10)
at Module.load (internal/modules/cjs/loader.js:950:32)
at Function.Module._load (internal/modules/cjs/loader.js:790:14)
at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:76:12)
at internal/main/run_main_module.js:17:47
[nodemon] app crashed - waiting for file changes before starting...

Connecting to the mongodb

I'm new in the MEAN developing, I'm developing a simple app, and for my first step I'm trying to connect to my mongodb, so I installed node, express, morgan,mongodb, mongoose.
So here is my code in index.js:
const express = require('express');
const morgan = require('morgan');
const app = express();
const { MongoClient } = require('./database');
// Settings
app.set('port', process.env.PORT || 3000);
// Middlewares
app.use(morgan('dev'));
app.use(express.json());
// Routes
// Starting the server
app.listen(app.get('port'), () => {
console.log('server on port', app.get('port'));
});
and then the code on my database.js:
const MongoClient = require('mongodb').MongoClient;
const uri = "mongodb+srv://duke:<password>#cluster0-dreyi.mongodb.net/test?retryWrites=true&w=majority";
const client = new MongoClient(uri, { useNewUrlParser: true });
client.connect(err => {
const collection = client.db("test").collection("devices");
console.log("horrorrrrrr");
// perform actions on the collection object
client.close();
});
module.exports = MongoClient;
I also try this code that is on the mongodb page to connect to the application:
const MongoClient = require('mongodb').MongoClient;
const uri = "mongodb+srv://duke:<password>#cluster0-dreyi.mongodb.net/test?retryWrites=true&w=majority";
const client = new MongoClient(uri, { useNewUrlParser: true });
client.connect(err => {
const collection = client.db("test").collection("devices");
// perform actions on the collection object
client.close();
});
Of course I change the password to the real one. Please keep in my today it's my first time I touch mongodb and also the MEAN full stack, and I spent too many hours stuck in this connection.
this is the error I get:
(node:5284) DeprecationWarning: current Server Discovery and Monitoring engine is deprecated, and will be removed in a future version. To use the new Server Discover and Monitoring engine, pass option { useUnifiedTopology: true } to the MongoClient constructor.
EDIT
#iLiA thanks for your reply ! I tried your code and ain't working, I will show you how I did it with the real password :
const url = 'mongodb+srv://duke:password#cluster0-dreyi.mongodb.net/test?retryWrites=true&w=majority';
const mongoose = require('mongoose');
mongoose.connect(url, {
useNewUrlParser: true,
useCreateIndex: true,
useUnifiedTopology: true,
useFindAndModify: false
})
.then(()=>{
console.log('congrats, problem solved')
})
.catch((err)=>{
console.log(`there is not a problem with ${err.message}`);
process.exit(-1)
})
module.exports = mongoose;
and the error is :
there is not a problem with Server selection timed out after 30000 ms
[nodemon] app crashed - waiting for file changes before starting...
Kind regards,
I am confused about why do you downloaded both mongodb and mongoose but here is mongoose solution
const mongoose = require('mongoose');
mongoose.connect(url, {
useNewUrlParser: true,
useCreateIndex: true,
useUnifiedTopology: true,
useFindAndModify: false
})
.then(()=>{
console.log('congrats, problem solved')
})
.catch((err)=>{
console.log(`there is a problem with ${err.message}`);
process.exit(-1)
})
EDIT:
As it seems you forgot to whitelist your IP address in mongo atlas.

Angular2 and ExpressJS API - Logged In Sessions Not working

Basically I have written and Angular2 frontend client that consists of a button, when you click this button it makes a very simple request to the expressJS and passportJS api using the following function:
socialLogin(){
window.location.href='http://api.example.io/auth/facebook';
console.log('social');
this.authenticationService.getProjectsMain();
}
Once that is finished everything is fine, I can visit the api url:
http://api.example.io/v1/api/me
in my browser and see my facebook data, my problem is that when I try to get this json data from the angular2 frontend service its as though the login has never happened even though I have it open in another tab and can see that there is data on the API subdomain. I am doing a get request to the api url and its getting nothing, because nothing is there. I am guessing that this is some kind of persistent cookie but I am unsure of how to put all this together.
My app.js server file
const express = require('express');
const passport = require('passport');
const Strategy = require('passport-facebook').Strategy;
const path = require('path');
const favicon = require('serve-favicon');
const logger = require('morgan');
const cookieParser = require('cookie-parser');
const bodyParser = require('body-parser');
const routes = require('./routes/index');
const loginfacebook = require('./routes/login-facebook');
const callbackfacebook = require('./routes/callback-facebook');
const standardLogin = require('./routes/standardlogin');
const me = require('./routes/me');
const app = express();
app.all('/*', function(req, res, next) {
// res.header("Access-Control-Allow-Origin", "*");
console.log('origin ' + req.headers.origin);
res.header('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');
res.header("Access-Control-Allow-Origin", req.headers.origin );
res.header('Access-Control-Allow-Credentials', true);
res.header("Access-Control-Allow-Headers", "X-Requested-With, Content-type");
next();
});
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
/*app.use(require('express-session')({
secret: 'keyboard cat',
resave: true,
saveUninitialized: true
}));*/
app.use(require('express-session')({
secret: 'keyboard cat',
cookie: {
path: '/',
domain: '.example.io',
maxAge: 1000 * 60 * 24, // 24 hours
},
resave: true,
saveUninitialized: true
}));
app.use(passport.initialize());
app.use(passport.session());
app.use('/', routes);
app.use('/auth/facebook', loginfacebook);
app.use('/callback/facebook', callbackfacebook);
app.use('/v1/api/login', standardLogin);
app.use('/v1/api/me', me);
app.listen(80);
module.exports = app;