Optimize Next.js 10 TypeScript Project by Caching MongoDb Connection in API Routes

I am currently in the process of transitioning next.js/examples/with-mongodb/util/mongodb.js to TypeScript so I can efficiently cache and reuse my connections to MongoDB within a TypeScript based next.js project. However, I am encountering a TypeScript error regarding cache.promise that states:

Type 'Promise<MongoClient | { client: MongoClient; db: Db; }>' is not assignable to type 'Promise<MongoClient>'

What is the correct way to declare the mongo property on global in order to satisfy the TypeScript requirements?

import { MongoClient, Db } from "mongodb";

const { DATABASE_URL, DATABASE_NAME } = process.env;

declare global {
  namespace NodeJS {
    interface Global {
      mongo: {
        conn: MongoClient | null;
        promise: Promise<MongoClient> | null;
      };
    }
  }
}

let cached = global.mongo;

if (!cached) {
  cached = global.mongo = { conn: null, promise: null };
}

async function connect() {
  if (cached.conn) {
    return cached.conn;
  }

  if (!cached.promise) {
    const opts = {
      useNewUrlParser: true,
      useUnifiedTopology: true,
    };

    cached.promise = MongoClient.connect(DATABASE_URL, opts).then((client) => {
      return {
        client,
        db: client.db(DATABASE_NAME),
      };
    });
  }
  cached.conn = await cached.promise;
  return cached.conn;
}

export { connect };

Answer №1

If you want to avoid caching your connection, take a look at the most recent version of Next.js with MongoDB from this example. I was directed to this project by experts on the official MongoDB forum who helped me troubleshoot.

It's recommended to utilize native solutions for better performance.

Answer №2

The data stored in the 'conn' property includes both MongoClient as well as the Db.

In your global declaration of mongo, you have only included the MongoClient. To address this issue, I suggest creating a new type called MongoConnection that encompasses both entities. See example code below.

type MongoConnection = {
  client: MongoClient;
  db: Db;
};

declare global {
  namespace NodeJS {
    interface Global {
      mongo: {
        conn: MongoConnection | null;
        promise: Promise<MongoConnection> | null;
      }
    }
  }
}

Answer №3

It appears that the solution is to define the mongo property as type any, as shown below:

declare global {
  namespace NodeJS {
    interface Global {
      mongo: any;
    }
  }
}

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

How to Use MongoDB Aggregation to Filter Data Based on Two

When an aggregation pipeline stage is executed, it generates the following collection: { _id : { airport : "SGF", minEffect : "security_delay", delayType : "arr_delay", } } { _id : { ...

Angular - Implementing validation for maximum character length in ngx-intl-tel-input

Utilizing the ngx-intl-tel-input package in my Angular-12 project multistep has been quite promising. Below is a snippet of the code: Component: import { SearchCountryField, CountryISO, PhoneNumberFormat } from 'ngx-intl-tel-input'; expor ...

Google Analytics in Next.js Missing Page Title Configuration

I recently set up Google Analytics on my Next.js website, but I'm encountering a strange issue where the analytics are not detecting my webpages and showing as (not set). Everything else seems to be functioning properly. I've double-checked that ...

A guide on integrating Global Styles using SCSS in NextJS

I've been trying to incorporate Global Styles into my NextJS Application, following the Documentation guidelines. However, despite writing my code correctly, the styles are not being applied. My styling language is SCSS, and I'm using TSX for my ...

Utilizing GridFS for efficient file storage in MongoDB with the seamless integration of Mongoose and AngularJS

When I first started, I had very little knowledge on how to save a file to a NoSQL MongoDB using Mongoose and Angular. After extensive research, I discovered that I needed to utilize GridFS to solve my problem. The challenge was finding a detailed explan ...

What could be causing Firebase to not recognize the ProjectId?

After providing serviceAccount information to Firebase, I am encountering an issue where it cannot detect the project id. Unfortunately, I have not been able to find a solution yet. This might be due to a syntax error, as I am not very familiar with the fi ...

What is the best way to map elements when passing props as well?

In my code, I am using multiple text fields and I want to simplify the process by mapping them instead of duplicating the code. The challenge I'm facing is that these textfields also require elements from the constructor props. import React, { Compon ...

Uploading files with Express using Multer

I'm having trouble uploading an image using multer because I keep getting the error message "uploads is not a function." Here's my code: var multer = require('multer'); var uploads = multer({dest: './images'}); app.post(&apos ...

Exploring the Importance of Secure User Input Handling in Node.js, Express.js, and MongoDB with Find and Insert Operations

A new set of REST services was developed using Express.js to query results from a Mongo Database. A simplified version of the code for one of the services is as follows: var express = require('express'); var app = express(); var bodyParser = r ...

Ways to recycle functional elements in Next.js 13 Server Components

Encountering a problem trying to separate the logic from the component due to this error message: Error: Event handlers cannot be passed to Client Component props. <textarea rows={18} placeholder=... onInput={function}> ...

Angular auto suggest feature

I am working with a dropdown in Angular that contains JSON data. The data is stored in a List named options and I need to display the name field in the dropdown list. My current task involves implementing an autocomplete search feature for this dropdown. ...

I encountered an issue with route handlers in Next.js version 13.2. Sadly, they are not

I am trying to implement an API on my website with the endpoint /api/popular-movie. Here is an overview of my file structure: https://i.stack.imgur.com/e8Pf8.png Additionally, this is my route.ts code: import { NextResponse } from "next/server"; ...

Why am I able to connect to mongo shell but not able to connect to mongodb using compass?

I'm facing a dilemma. While I can successfully connect to mongodb using the shell, I am unable to do so with Compass, whether through a connection string or manual input in the fields provided. Here's the connection command I use in the shell: m ...

The output.library.type variable in WebPack is not defined

Currently, I am delving into WebPack with a shortcode. As part of my learning process, I am working on a code snippet that involves calculating the cube and square of a number, which are then supposed to be stored in a variable outlined in the webpack.conf ...

How to retrieve the page URL or hostname within a NextJs Project?

How can I retrieve the complete URL or website hostname on a Static Site Generator similar to the image below? I attempted using window.location.hostname, but unfortunately, it did not yield results. The error message displayed was: window not defined. ...

A guide on connecting multiple select components to a unified Angular 6+ reactive form without triggering redundant updates

I am facing an issue where I need to connect multiple input components to a single angular reactive form, but encounter two main obstacles: By default, only the form in which user input occurs gets updated If I use [(ngModel)] it does work, but it trigge ...

Bidirectional data binding in angular 12 reactive forms

After working with angular for a while, I encountered an issue while trying to implement two-way binding. The code snippet below is where I'm facing difficulty. Since the use of [(ngModel)] has been deprecated in Angular 12 within formGroup, finding ...

Looking to adjust the API response to fit the necessary JSON format for an Angular project?

A modification is needed in the API response to align with the required JSON format provided below. The current responses and the desired format are detailed for reference. Assistance is appreciated. The current representation of individual's data ne ...

Encountering the error message "ERR_REQUEST_RANGE_NOT_SATISFIABLE" while utilizing the Azure Text To Speech API within

Utilizing Microsoft Azure's Text-to-speech API, my objective is straightforward: trigger synthesized speech to play in the browser upon clicking a button. My approach involves employing nextJS API routes to send a request to Azure and then leveraging ...

Using Typescript literal types as keys in an indexer is a common practice

Can we create a TypeScript literal type that acts as a string key in an indexer? type TColorKey = 'dark' | 'light'; interface ColorMap { [period: TColorKey]: Color; } But when attempting this, the following error is generated: An ...