The readiness status of the mongoose connection is resulting in a TypeError: Unable to access undefined properties (reading 'readyState')

I've been utilizing Mongo Memory Server for my unit tests successfully, but all of a sudden mongoose.connection is returning as undefined. This has left me completely baffled! I would have anticipated readyState to at least be 0.

import * as mongoose from 'mongoose';
import { MongoMemoryServer } from 'mongodb-memory-server';

let con: mongoose.Connection;
let mongoServer: MongoMemoryServer;

export const connectToDatabase = async () => {
  mongoServer = await MongoMemoryServer.create();
  await mongoose.connect(mongoServer.getUri(), {})
    .catch((err) => {
      console.log(err); // no error is thrown
    });
    con = mongoose.connection; // Why is this turning out to be undefined?!
    console.log(con.readyState); // This line seems to be triggering the error
}

Answer №1

When the esModuleInterop option is set to true or unset in the tsconfig.json file, use the default import syntax import mongoose from 'mongoose'.

If the esModuleInterop option is set to false or unset, use the namespace import syntax

import * as mongoose from 'mongoose'
.

import mongoose from 'mongoose';
import { MongoMemoryServer } from 'mongodb-memory-server';

let con: mongoose.Connection;
let mongoServer: MongoMemoryServer;

export const connectDB = async () => {
  mongoServer = await MongoMemoryServer.create();
  await mongoose.connect(mongoServer.getUri(), {})
    .catch((err) => {
      console.log(err);
    });
  con = mongoose.connection;
  console.log('con.readyState: ', con.readyState);
}

connectDB();

Logs:

 ⚡  npx ts-node ./index.ts
con.readyState:  1

Package versions:

"mongodb-memory-server": "^8.12.2",
"mongoose": "^7.1.1",

Answer №2

import * as mongoose from 'mongoose';
import { MongoMemoryServer } from 'mongodb-memory-server';

let connection: mongoose.Connection;
let memoryServer: MongoMemoryServer;

export const establishConnection = async () => {
  memoryServer = await MongoMemoryServer.create();
  await mongoose.connect(memoryServer.getUri(), {})
  .catch((error) => {
    console.log(error);
  });
  connection = mongoose.connections[0];
  console.log(connection.readyState);
}

To address the issue, I made a change by replacing "mongoose.connection" with "mongoose.connections[0]" as shown in the code snippet above. It's still unclear whether this is related to an aspect of mongoose version 7.2.0 or is specific to my local development environment setup.

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

What could be causing the empty object return from the Async function in my Typescript code on Next JS?

Encountering issues with an async function. In the ../lib folder, I have a class for handling data from an API website. However, when attempting to load the API data within an async function, I encounter difficulties. The async function does not return a ...

Storing file paths as string variables in Angular: a quick guide

I'm working with this line of code that selects all the files in a folder. <input type="file" id="filepicker" name="fileList" (change)="saveFolderLocation($event)" webkitdirectory/> My goal is to determin ...

Is it possible for a conditional type in TypeScript to be based on its own value?

Is it possible to use this type in TypeScript? type Person = { who: string; } type Person = Person.who === "me" ? Person & Me : Person; ...

Displaying Typescript command line options during the build process in Visual Studio

As I delve into the world of VS 2015 Typescript projects, I find myself faced with a myriad of build options. Many times, the questions and answers on Stack Overflow mention command line options that I'm not completely familiar with, especially when i ...

Learn how to successfully import a webp image into a React TypeScript project

I have looked everywhere for the answer, but I can't seem to find it When trying to import a *.webp image in typescript, you need to create a declaration file, like declaration.d.ts The declaration file should contain something similar to the foll ...

Type arguments cannot be accepted in untyped function calls.ts(2347)

My user schema in typescript includes the following interface: interface IUser{ name: string; email: string; password: string; isAdmin: boolean; } Check out the user schema below: const UserSchema = new Schema<IUser>( { name: { type ...

Facing issues with the Node.js mongoose module's functionality when deployed on Heroku

Recently, our website started encountering an Application Error: "An issue occurred within the application preventing your page from loading. Please try again shortly. If you are the owner of the application, review your logs for more information." Upo ...

error: encountering issue with Vue TypeScript Jest tests - '$store' property is undefined

I've been facing issues with my tests failing after a recent npm install. I've tried adjusting versions up and down, but haven't had any success. Interestingly, the $store isn't directly used in any of the components or tests. Despit ...

Looking for a way to go through a set of documents in an array and calculate the sum of a specific property in JSON using the $cond

Here's an array of JSON data: let x = [{"Data":"Chocolate","Company":"FiveStar"},{"Data":"Biscuit","Company":"Parle"},{"Data":"Chocolate","Company ...

What's preventing me from using just one comparison condition in TypeScript?

The issue at hand is quite simple: An error occurred because I tried to compare a number with a 'Ref<number>' object. It seems ridiculous that I can't compare two numbers, but as I am new to Typescript, I would greatly appreciate some ...

Tips for utilizing the $or operator in a URL query string with a node.js express mongoose backend

Is there a recommended way to incorporate the $or operator in a URL query string for a customizable client query that involves multiple fields in a node.js powered RESTful API? For example, if we have objects like [{ A: 1, B: 2, C: 42 }, { A: 3, ...

Is there a problem with the props being passed? Can someone verify this

Blockquote Having trouble passing props, Parent component: props: { data: { type: Object as PropType<FormatOrderItem>, default: () => {} } I'm facing an issue when trying to pass props from the parent component to the ch ...

The string is being added to an array twice

I am managing two sets of lists where strings will be transferred between them. One set contains a list of strings for searching purposes. The other set contains the same list of strings but is not used as a filter. The second set functions in a similar ...

Tips for troubleshooting the error "Cannot locate module mp3 file or its associated type declarations"

https://i.sstatic.net/q4x3m.png Seeking guidance on resolving the issue with finding module './audio/audio1.mp3' or its type declarations. I have already attempted using require('./audio/audio1.mp3'), but continue to encounter an error ...

Verifying completed fields before submitting

I'm in the process of designing a web form for users to complete. I want all fields to be filled out before they can click on the submit button. The submit button will remain disabled until the required fields are completed. However, even after settin ...

Issue with Moment Js: Unable to change date with time zone function

Trying to convert a UTC date and time to local time ("Europe/Paris") using moment's timezone function, but encountering issues. The code I am using is: var m = moment.tz(this.startTime, 'Europe/Paris'); this.startTime = m.format("YYYY-MM-DD ...

Tips for dynamically updating page titles in the browser tab using Angular 8

In the application I am developing, there is a list of employees that when clicked on, navigates to that employee's details. I want the browser title to display information specific to each employee, such as "Employee Name: Employee Number". The same ...

Is it feasible to incorporate a multi-level navigation menu into the "NavItem" component using MaterialUI with TypeScript?

Instructions for creating a multi-level navigation menu using MaterialUI and TypeScript: To the existing '/questions' section, it is desired to include the following 2 navigation menus: /questions/Tags /questions/Users This should resemble the ...

Revamping an npm package on GitHub

Currently, I am managing a project that has gained popularity among users and has received contributions from multiple individuals. The next step I want to take is to convert the entire library into TypeScript, but I am unsure of the best approach to ach ...

How to easily scroll to the top of the previous page in Angular 8

In my Angular 8 application, there are buttons that are meant to take the user back to the previous page when clicked. While the functionality works as expected, I am facing an issue where the page does not automatically scroll to the top upon navigating ...