Can someone please help me identify the issues in my code? I'm facing difficulties while working with Express and connecting to MongoDB

I'm completely stumped on what's causing the issue in my code.

This error message keeps popping up:

TypeError: Class constructor MongoStore cannot be invoked without 'new'

Does anyone have any insights into this problem? And is there a solution available?

I've spent hours trying to identify my mistake with no luck.

    require('dotenv').config()
    
    const express = require('express')
    const app = express()
    const mongoose = require('mongoose')
    
    mongoose.connect(process.env.CONNECTIONSTRING, { useNewUrlParser: true, useUnifiedTopology: true })
        .then(() => {
            app.emit('pronto')
        })
        .catch(e => console.log(e))
    
    
    const session = require('express-session')
    const MongoStore = require('connect-mongo')(session)
    
    
    const routes = require('./routes')
    const path = require('path')
    const { middleGlobal } = require('./src/middlewares/middleware')
    
    app.use(express.urlencoded({ extended: true }))
    
    app.use(express.static(path.resolve(__dirname, 'public')))
    
    const sessionOptions = session({
        secret: 'hdfkajdkk58fj',
        store: new MongoStore({ mongooseConnection: mongoose.connection }),
        resave: false,
        saveUninitialized: false,
        cookie: {
            maxAge: 1000 * 60 * 60 * 24 * 7,
            httpOnly: true
        }
    })
    
    
    app.use(sessionOptions)
    app.use(flash())
    
    app.set('views', path.resolve(__dirname, 'src', 'views'))
    app.set('view engine', 'ejs')
    
    // Our custom middleware
    app.use(middleGlobal)
    
    app.use(routes)
    
    app.on('pronto', () => {
        app.listen(3000, () => {
            console.log("Server is running on port 3000")
            console.log("Visit http://localhost:3000")
        })
    })

Answer №1

Based on information from the documentation, the recommended approach for integrating connect-mongo with express-session is as follows:

const session = require('express-session');
const MongoStore = require('connect-mongo');

app.use(
  session({
    secret: 'hjlsdf89sadf',
    store: MongoStore.create({ mongooseConnection: mongoose.connection }),
    resave: false,
    saveUninitialized: false,
    cookie: {
      maxAge: 1000 * 60 * 60 * 24 * 7,
      httpOnly: true,
    },
  })
);

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Deliver a downloadable CSV file as a response from a Next.js application

I have a piece of code that allows me to retrieve a downloadable file upon request. const csv = converter.json2csv(data); return new Response(csv, { headers: { 'Content-type': 'text/csv', 'Content-Disposition': &apos ...

What is the process for sending an image as input to a Django view using an Angular frontend?

I currently have a django web api with an angular frontend that allows users to upload and view images. My goal now is to expand this functionality: when the user clicks the "segment" button (see image), it should send the corresponding image to my python ...

reveal concealed section and seamlessly glide to specified location inside the secret compartment

I have implemented a feature on my website where hidden divs are revealed one at a time, with the screen scrolling to display each specific div. While this code functions well, I am now looking to enhance it by opening the hidden div and smoothly scrolling ...

How can I invoke a function within a directive-generated HTML element's scope?

I created a custom directive that utilizes element.html() to set the HTML content. Within this HTML code, I would like to be able to invoke functions from the scope where the directive is being used. Here's an example: app.directive('myDirective ...

The Node.contains() function in JavaScript does not verify the presence of inner child elements

I have developed a custom DatePicker component for my React app and I am facing an issue with hiding it on outside click, similar to how I handled other components like Select Dropdown. To address this problem, I created a custom hook: export default (ref, ...

Unlocking the Secret: How to Bind a Global Touch Event Handler in Angular 4 to Prevent iOS Safari Page Drag

The issue at hand is that within my Angular 4 application, there is a D3.js chart that relies on user touch input for dragging a needle to a specific value. The drag functionality is triggered by 'touchstart', while the registration of the final ...

Showcasing PHP variables within HTML using jQuery

I am currently looking for the best way to showcase information stored in a PHP variable, retrieved from a MySQL database. My initial thought was to use jQuery. Here are my questions: When a user inputs a number into a field, I receive that Member' ...

Retrieve the HTML contents of a cell that contains a checkbox with the value of "jquery"

Here is an example of a table row: <tr> <td><input type='checkbox' name='post[]' value="1"></td> <td>08-Apr-2014</td> <td>injj team</td> <td>merchant.testyy.com</ ...

Mongodb offers the flexibility of unlimited nesting for categories, sub-categories, and sub-sub-categories, making it easy

I recently set up an online store but I'm looking to make some changes to it. I want to allow users to create an unlimited number of categories and subcategories. How should I go about implementing this on my Nodejs (express) and MongoDB (mongoose) ba ...

Managing ajax requests timeouts while abiding by the browser's connection limitations

Encountering an issue with ajax requests and fixed timeouts, I've resorted to using this straightforward code snippet: $.ajax({ url: "test.html", error: function(){ //do something }, success: function(){ //do something ...

Show a single jQuery Validation error

I am struggling with displaying an error message at the top if validation fails, without using the errorPlacement option. Instead, I want to showcase the message in a Bootstrap alert box. Below is the HTML code snippet: <form method="POST" action="/ro ...

Is there a way to access a computed property within methods?

Currently, I am utilizing this particular package to implement infinite scrolling in Vue. In order to continuously add new elements during each scroll, I fetch JSON data from my API server and store it in a data object. Subsequently, I divide the array in ...

The navigation underline stays in place even after being clicked, and also appears below

Take a look at this js fiddle I've managed to create the underline effect on the navigation links when the user hovers over them. However, the underline only stays visible until the user clicks elsewhere on the screen. How can I make it persist as l ...

What's Next? Redirecting Pages in Node.js Express after Handling POST Requests

Is it possible to redirect to a different page from a post request? module.exports = function(app) { app.post('/createStation', function(request, response){ response.redirect('/'); //I'm having trouble getting ...

JQuery form not triggering the submit event

Currently, I am facing some issues with my code while trying to trigger on submit event on a form and validate it. The main problems I encountered are that the onsubmit event is not being triggered, and the input field of type email is not validated proper ...

Create HTML content dynamically with JavaScript and then utilize AngularJS to interpret and render it

I am creating an HTML table that looks like this: <table id="#webappname"> <tr ng-repeat="data in d"> <td>1 {{data}}</td> <td>2 hey !</td> </tr> </table> To create this, I am using a ...

Express does not render the page; it only retrieves and returns JSON data

An issue arises when the server returns only JSON instead of the page after a reload. I am utilizing React and serving static files from the build folder. Express is handling routing, and this problem only occurs in production mode; everything works fine ...

Node Js seems to be taking quite a while to output to the console

Hello, this is my first time posting on Stack Overflow so please bear with me if I make any mistakes. I created a button that, when clicked, decrements the quantity by one. After updating the UI, I send the data to the server. However, when I console log t ...

Looking to extract the first URL from a string using JavaScript (Node.js)?

Can someone help me figure out how to extract the first URL from a string in Node.js? " <p> You left when I believed you would stay. You left my side when i needed you the most</p>**<img src="https://cloud-image.domain-name.com/st ...

What could be the reason for loopback generating the error message: The `ModelDefinition` object is not considered valid?

Currently experimenting with Strongloop. Going through the "Getting Started" tutorials to understand the basic functionalities. Using Windows and PostgresSQL, I set up a new datasource and made changes to the model-config.json to switch the default models ...