NestJS API experiencing issues connecting to MongoDB due to empty index keys

My goal is to create an API with NestJS using TypeORM. Initially, I had set up the API to work with Postgres, but now I need to migrate it to MongoDB. After making the necessary changes, the connection is established successfully. However, I encounter an immediate error that says:

MongoError: Index keys cannot be empty.

app.module.ts

TypeOrmModule.forRoot({
      type: DATABASE_TYPE,
      url: DATABASE_HOST,
      port: DATABASE_PORT,
      username: DATABASE_USERNAME,
      password: DATABASE_PASSWORD,
      database: DATABASE_NAME,
      entities: [`${__dirname}/**/*.entity.{ts,js}`],
      synchronize: DATABASE_SYNCHRONIZE,
    })

config.ts

export const DATABASE_TYPE: any = process.env.DATABASE_TYPE || 'postgres';
export const DATABASE_USERNAME: string =
  process.env.DATABASE_USERNAME || 'admin';
export const DATABASE_PASSWORD: string =
  process.env.DATABASE_PASSWORD || 'asdsddddd';
export const DATABASE_HOST: string = process.env.DATABASE_HOST || 'localhost';
export const DATABASE_PORT: number = Number(process.env.DATABASE_PORT) || 5432;
export const DATABASE_NAME: string = process.env.DATABASE_NAME || 'nestjs-db';
export const DATABASE_SYNCHRONIZE: boolean =
  Boolean(process.env.DATABASE_SYNCHRONIZE) || true;

.env

DATABASE_TYPE=mongodb
DATABASE_USERNAME=admin
DATABASE_PASSWORD=admin
DATABASE_HOST=mongodb+srv://steeve:<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="4c3f7e7d2d0c2b3e2d3c243d20617c23272b27622123222b23282e62222938">[email protected]
DATABASE_SYNCHRONIZE=true

Answer №1

After conducting some research, I stumbled upon an issue logged on github: https://github.com/typeorm/typeorm/issues/4267 One of the ways to resolve this is by disabling the synchronize option (or eliminating it altogether):

synchronize: false

Answer №2

Ensure that both useNewUrlParser and useUnifiedTopology are set to true.

This is how my connection looks in AppModule :

TypeOrmModule.forRoot({
      type: config.DB_1_TYPE,
      host: config.DB_1_HOST,
      port: config.DB_1_PORT,
      database: config.DB_1_DATABASE,
      useNewUrlParser: true,
      useUnifiedTopology: true,
      entities: [
        'build/**/**.entity.js',
        '**/**.entity.js',
        'src/**/**.entity.js',
      ],

Here's what I have in my .env file:

DB_1_URI=mongodb://localhost:27067
DB_1_TYPE=mongodb
DB_1_HOST=localhost
DB_1_DATABASE=my-database
DB_1_USERNAME=root
DB_1_PASSWORD=root
DB_1_PORT=27067

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

Exploring Angular 4.0: How to Loop through Numerous Input Fields

I am looking to loop through several input fields that are defined in two different ways: <input placeholder="Name" name="name" value="x.y"> <input placeholder="Description" name="description" value"x.z"> <!-- And more fields --> or lik ...

What is the best way to ensure that Interface (or type) Properties always begin with a particular character?

I attempted to tackle this assignment using template literals, but unfortunately, I wasn't successful. Here is the interface that I am working with: interface SomeInterface { '@prop1': string; '@prop2': string; '@ ...

Library for Typescript on npm

My project involves a collection of base classes in TypeScript. Within a web application built with React and written in TypeScript, I am looking to integrate a library called 'Plain Old TypeScript objects', which defines all the data types. Let& ...

Swagger is refusing to cooperate because my model's attributes are set to true

Currently delving into Swagger and its documentation functionality through a YAML file. Previously, I had used @swagger in the controller file and everything worked fine. However, when attempting to transition to a YAML file for better organization, issues ...

The attribute 'constructor' is not found on the 'T' type

I'm currently working on a project using Next.js and TypeScript. I've come across an issue where TypeScript is giving me the error "Property 'constructor' does not exist on type 'T'" in my generic recursive function. Here&apo ...

Is there a way to initiate validations for inputs within ReactiveForms?

After creating a form using Reactive Forms, I have implemented functionality for users to set a new password. The process involves entering both the old and new passwords, as well as confirming the new password. Throughout development, I considered the fol ...

Encountering an issue with the form onSubmit function in React TypeScript due to an incorrect type declaration

I have a function below that needs to be passed into another component with the correct type definition for updateChannelInfo, but I am encountering an issue with the type showing incorrectly: const updateChannelInfo = (event: React.FormEvent<HTMLFormEl ...

Older versions of javascript offered the assurance of a promise

Working with TypeScript and the latest ECMAScript 6 feature Promise at the moment. I'm wondering if it's possible to use Promise even if my TypeScript code is compiled into an ECMAScript 3 js-file, considering that Promise wasn't available i ...

Leveraging Criteria API for constructing dynamic queries in Spring Data MongoDB

I have a list that contains specific IDs which I need to retrieve from the database. The list looks something like this: List<someObject> filterCriteria = [{"name":"somename", "value":"someValue"},{"value":"randomValue"}] These filters give me two ...

Using React and Typescript: Populating an array within a For Loop using setTimeout is not happening sequentially or at all

I'm currently working on a function that animates images of random cars moving across the screen. My goal is to stagger the population of the "carsLeft" array using setTimeout, where I will eventually randomize the delay time for each car. Everything ...

What is the reason for the allowance of numeric keys in the interface extension of Record<string, ...>

I am currently working on a method to standardize typing for POST bodies and their corresponding responses with API routes in my Next.js application. To achieve this, I have created an interface that enforces the inclusion of a body type and a return type ...

Using query parameters in Angular to interact with APIs

One scenario involves a child component passing form field data to a parent component after a button press. The challenge arises when needing to pass these fields as query parameters to an API endpoint API GET /valuation/, where approximately 20 optional p ...

unable to retrieve access-token and uid from the response headers

I am attempting to extract access-token and uid from the response headers of a post request, as shown in the screenshot at this https://i.sstatic.net/8w8pV.png Here is how I am approaching this task from the service side: signup(postObj: any){ let url = e ...

Encountering issues with retrieving application setting variables from Azure App Service in a ReactJS TypeScript application resulting in '

My dilemma lies in my app setup which involves a Node.js runtime stack serving a ReactJs Typescript application. I have set some API URLs in the application settings, and attempted to access them in ReactJs components using process.env.REACT_APP_URL, only ...

Reattempting a Promise in Typescript when encountering an error

I am currently working on a nodeJS application that utilizes the mssql driver to communicate with my SQL database. My goal is to have a unified function for retrieving a value from the database. However, in the scenario where the table does not exist upon ...

Create a unique type in Typescript that represents a file name with its corresponding extension

Is there a way for me to specify the type of a filename field in my object? The file name will consist of a string representing the name of the uploaded file along with its extension. For instance: { icon: "my_icon.svg" } I am looking for a ...

Typescript integration with Sequelize CLI for efficient database migrations

According to the Sequelize documentation, it claims to work with Typescript. However, for it to be fully functional in a production environment, DB migration scripts are necessary. The issue arises when using the Sequelize CLI as it only generates and runs ...

An easy method to define argument types for every function type in TypeScript

How can I assign argument types to each function type in TypeScript? Each function has a parameter associated with it. [Example] type F1 = (arg: number) => void; type F2 = (arg: string) => void; const caller = (f: F1 | F2) => (n: number | strin ...

Upgrading from Angular 5 to 6: Embracing the RxJS Changes without the crutch of rxjs

Currently, I am facing the challenging task of migrating a project from Angular 5.2.11 to version 6.0.0. The main issue I'm encountering is with RxJS 6 (which is essential for Angular versions above 6). Here's an example of one of the errors that ...

Efficiently loading Ionic 3 components within a tab with lazy-loading functionality

Need help with adding a new tab to your project using lazy-loading? You can utilize the @IonicPage decorator for setting up a page as the root of a tab. To implement this, create a new page: // module import { NgModule } from '@angular/core'; ...