`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**`
Iām trying to connect to RDS and seed data.
ormconfig.js
const entities = process.env.NODE_ENV === 'test' ? ['./src/**/**/*.ts'] : ['./dist/**/**/*.js'];
const logging = process.env.NODE_ENV !== 'test';
module.exports = {
type: 'postgres',
host: 'rds.ap-northeast-1.rds.amazonaws.com',
port: 5432,
username: 'postgres',
password: 'password',
database: 'db',
synchronize: true,
migrationsRun: false,
logging,
migrations: [`${__dirname}/dist/migration/*.js`],
entities,
};
// # sourceMappingURL=ormconfig.js.map
Error
ā Database connection failed! Check your typeORM config file.
RDS is running for sure and all the values of DB are from AWS Secrets Manager, so they are correct.
Why is this happening?
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...
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
}) }));
I am trying to set up a keystone project with a remote database server hosted on mLab. I am using this guide here https://itnext.io/building-a-node-cms-with-keystonejs-mongo-db-react-and-redux-part-i-ae5958496df2
I have edited the mongo url in the keystone.init() configuration, with my mLab database URL, and managed to run the project.
'mongo': 'mongodb://*username*:*password*#ds127624.mlab.com:27624/keystone',
However, I am unable to login as a user.
The login page returned:
"The email and password you entered are not valid."
Do I need to do some more configurations for it to work properly?
....
user.js
var keystone = require('keystone');
var Types = keystone.Field.Types;
var User = new keystone.List('User');
User.add({
name: { type: Types.Name, required: true, index: true },
email: { type: Types.Email, initial: true, required: true, index: true },
password: { type: Types.Password, initial: true },
canAccessKeystone: { type: Boolean, initial: true },
});
User.register();
0.0.01-admin.js file
var keystone = require('keystone');
var User = keystone.list('User');
exports = module.exports = function (done) {
new User.model({
name: { first: 'admin', last: 'user' },
email: 'admin#keystonejs.com',
password: 'admin',
canAccessKeystone: true,
}).save(done);
};
For remote database with password you also have to add authsource option. basically add ?authSource=admin to your mongo url. admin is default db, you can change that as well
mongodb://*username*:*password*#ds127624.mlab.com:27624/keystone?authSource=admin