When working with Mongoose and TypeScript, encountering the 'connect' error from mongoose can be frustrating and disruptive to your

After attempting to start the server, an error message is displayed:

this.mongo.connect('mongodb://localhost:27017/tsnode', { ^ TypeError: Cannot read property 'connect' of undefined

import express from 'express';
import mongoose from 'mongoose';
import cors from 'cors';

class App {
  public express: express.Application;

  public mongo: mongoose.Mongoose;

  constructor() {
    this.express = express();
    this.database();
    this.middlewares();
    this.routes();
  }

  private middlewares(): void {
    this.express.use(express.json());
    this.express.use(cors());
  }

  private database(): void {
    this.mongo.connect('mongodb://localhost:27017/tsnode', {
      useUnifiedTopology: true,
    });
  }

  private routes(): void {
    this.express.get('/', (req, res) => res.send('Hello World!'));
  }
}

export default new App().express;

Answer №1

Make sure to initialize the `mongo` variable in the constructor function before using it in your code. Here is an example:

  constructor() {
    this.express = express();
    this.mongo= mongoose;  // Initialize mongo variable
    this.database();
    this.middlewares();
    this.routes();
  }

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

Passing a string array from View to Controller using Url.Action in MVC framework

I am facing an issue where I have a method that returns an array (string[]) and I am attempting to pass this array of strings into an Action. However, I am currently unable to pass my parameters as expected. Being new in MVC3, I would appreciate any insi ...

What is the best way to stop webpack from generating typescript errors for modules that are not being used?

The directory structure is set up as follows: └── src ├── tsconfig.json ├── core │ ├── [...].ts └── ui ├── [...].tsx └── tsconfig.json Within the frontend, I am importing a limi ...

Creating a stunning HTML 5 panorama with GigaPixel resolution

Interested in creating a gigapixel panorama using HTML 5 and Javascript. I found inspiration from this example - Seeking advice on where to begin or any useful APIs to explore. Appreciate the help! ...

Automatically resizing images in a canvas when their resolution exceeds the canvas size in HTML5

I am currently using Html5, fabric.js, and JavaScript to upload multiple images to a canvas. However, there are instances where the uploaded image size exceeds that of the canvas. I am looking for a way to ensure that the image is set to a fixed size. v ...

What are some effective ways to test React Router using Jest?

Just starting out with Jest testing and looking to test the code below. import React from "react"; import "./ButtonLogin.css"; import { Link } from 'react-router-dom'; function ButtonLogin() { return ( <Link to ...

Creating a personalized cover for devextreme column in datagrid: A Step-by-Step Guide

I have encountered an issue with wrapping a Column inside my DataGrid. My goal is to create a customized component that generates a Column with the correct formatting. For instance, I want to develop a ColumnDate component that includes specific date forma ...

The OrbitControls feature in Three.js seems to be malfunctioning

When I try to execute the script, an error message appears in the console saying "THREE.OrbitControls is not a constructor". https://i.sstatic.net/H5ap3.png What am I doing wrong? The code I used was taken from a manual. var controls; controls = new ...

How are these AJAX Parameters utilized in Wikipedia's API?

Currently analyzing a CodePen snippet that utilizes Wikipedia's API to allow users to search for any item. The search engine displays the first 10 results with brief summaries. Analyzing code written by others is, in my opinion, one of the most effect ...

Maintaining the selected option on page refresh with React Remix

I have a dropdown menu with 2 choices (en, no) for switching the language when onChange event occurs. To save the selected language, I am using localStorage. Due to the server-side rendering in Remix, direct access to localStorage is not possible. Therefo ...

Storing embedded documents in Cassandra's data model

When it comes to Cassandra, how can we store embedded documents in a collection similar to MongoDB? Specifically, how would we go about storing the following sample JSON representation? UserProfile = { name: "user profile", Dave Jones: { email: {name ...

The second guard in Angular 5 (also known as Angular 2+) does not pause to allow the first guard to complete an HTTP request

In my application, I have implemented two guards - AuthGuard for logged in users and AdminGuard for admins. The issue arises when trying to access a route that requires both guards. The problem is that the AdminGuard does not wait for the AuthGuard to fini ...

An issue arises when trying to loop using a while loop within an HTML structure

I have a small project with a predefined format, where I need to select a value from a dropdown menu and use that value to fetch data from a database and display it in HTML. While I am able to retrieve the data from the database based on the selected value ...

What could be causing the type error in Vue 3.3 when using a generic v-for key?

My application is built on Vue 3.3.4 with the latest support for generics in single file components. One of the components I'm working on is a generic list, which iterates over a set of items passed as a prop. There is also a prop called itemKey, used ...

Continuously incorporating Ajax requests into a queue

I'm currently tackling a new feature at work and find myself at a crucial point. Despite being unfamiliar with Ajax, I am determined to set up a manual queue to handle the requests instead of relying on the browser. After some research and referring t ...

Placeholder for a constructor property method

Currently, I am in the process of writing unit tests for a function that utilizes the twilio-node package to send SMS messages. The specific function I am focusing on testing, both for arguments passed and number of times called, is Twilio.prototype.messag ...

Tracking locations in real time with the AR.js framework

Is it possible to utilize the AR.js web framework for creating an Augmented Reality web app that helps users navigate from their current location to a specific destination with coordinates (lat, long)? I am looking to have it compatible with Chrome/Safari ...

Why is it necessary to include the spread operator before an array of objects?

Currently delving into Angular and stumbled upon a code snippet that seems a bit cryptic to me. The function I'm working with returns an array of objects as Observable<Product[]>: connect(): Observable<Product[]> { const dataMutati ...

jQuery unable to locate elements or update class following AJAX response

My jQuery.on() event functions are working great when bound to specific elements like "a.my-link". However, I have one function that is bound to the document or body and then traverses multiple elements with the same class attribute. Certain lines in this ...

Javascript: Harnessing Textbox Arrays for Improved Functionality

Check out the form displayed below. <form id="upload_form" enctype="multipart/form-data" method="post"> <input type="text" name="name[]" id="name"><br> <input type="text" name="name[]" id="name"><br> <input type="fil ...

Monitoring the "signed in" status within an AngularJS platform

I'm feeling a bit lost as I navigate my way through Angular. As a newcomer, I find myself writing quite a bit of code to keep track of the logged-in state. However, this approach seems fragile and unreliable. Currently, I rely on a global variable to ...