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

What is the best method to adjust the width of the PrimeNG ConfirmDialog widget from a logic perspective

Currently utilizing "primeng": "^11.2.0" and implementing the ConfirmDialog code below this.confirm.confirm({ header: 'Announcement', message: this.userCompany.announcement.promptMsg, acceptLabel: this.userCompany.announcement ...

IntelliJ IDEA does not support the recognition of HTML tags and directives

I seem to have lost the ability to switch between my HTML and TS files in Intellij IDEA; the tags, directives, and autocompletion in HTML are no longer working. Additionally, I'm receiving some warnings: https://i.stack.imgur.com/QjmNk.png Is there ...

Having trouble utilizing HTML Canvas in the newest release of Angular and TypeScript

After extensive searching on the internet, I have not been able to find any working examples of using HTML canvas in Angular. It seems that changes in syntax in Typescript and Angular's newer versions have rendered all existing solutions obsolete. I ...

What is the process for sending a parameter in getStaticProps within Next.js

Is there a way in NextJS to call an API when a user clicks the search button and display the relevant result? Thanks for your input! The API I'm currently utilizing is , with "Steak" referring to the specific food item of interest. In my development ...

Data is not displaying correctly in the Angular Material Table

I'm currently trying to build a mat table based on an online tutorial, but I'm facing a problem where the table appears empty even though I have hard coded data. As someone new to Angular and HTML/CSS, I'm struggling to understand why the ma ...

Conditional Rendering with Next.js for Smaller Displays

I've implemented a custom hook to dynamically render different elements on the webpage depending on the screen size. However, I've noticed that there is a slight delay during rendering due to the useEffect hook. The conditionally rendered element ...

Tips for repairing damaged HTML in React employ are:- Identify the issues

I've encountered a situation where I have HTML stored as a string. After subsetting the code, I end up with something like this: <div>loremlalal..<p>dsdM</p> - that's all How can I efficiently parse this HTML to get the correct ...

Error: Attempting to access property 'error' of an undefined object resulted in an unhandled exception

I encountered an error when using the handleSubmit function in the Register component: Uncaught (in promise) TypeError: Cannot read property 'error' of undefined. Below, you can see the code for the component, how I fetch API data, and the Next. ...

A guide on extracting the current website URL in a React application

I wanted to find a method to duplicate the text from a URL so that users could easily share the link with others. ...

Dynamic routing in Next.js with express leads to the refreshing of the page

I am facing an issue with my Next.js blog application that I built using an express custom browser. Whenever I click on a Link to route to '/blog/article-1', the page refreshes upon arrival at the destination. How can I prevent this from happenin ...

What is the best way to access the data being sent to a router link in Angular?

After navigating to the user page using the router sample below, how can I retrieve the details once it reaches the user page? I need to verify in my user.component.ts that the navigation is triggered by this [routerLink]="['user', user.id, &apo ...

Having trouble deploying my Next.js 13 app with Firestore to Firebase

Having trouble deploying my Next.js app that uses Firestore. Whenever I try to deploy it with Firebase, I encounter the following issue: https://i.stack.imgur.com/ZLiUb.png During setup, I followed these steps: - firebase init - selected Hosting - Chose ...

Next-redux-wrapper displays a Typescript warning if the state is not present or cannot be assigned to its specified types

I am currently using next-redux-wrapper and encountering two type errors. Has anyone else experienced this issue before, and if so, how did you resolve it? Despite the errors, the code is functional, and I can view my state in the redux-devtools-extensio ...

Crafting insightful blog entries within a Github repository using Next JS

My goal is to establish a distinct Github repository to store blog post information and then integrate it into my Next.js website. Does anyone know if this is achievable? Any guidance would be greatly appreciated. I attempted searching for solutions onli ...

Managing Geolocation in Ionic2 presenting challenges

Attempting to utilize Geolocation in ionic2 for device location access. Referred to the official documentation on https://ionicframework.com/docs/native/geolocation/. Successfully installed the necessary packages: $ ionic plugin add cordova-plugin-geoloca ...

Steps to set angular for all items in the dropdown menu:

I am currently working on implementing a dropdown feature within my Angular application. The dropdown will display a list of shops, and when a shop is selected, it will show the content related to that particular shop. I need to add a new item called "ALL ...

Initiate a timer with intervals of 3 seconds upon reaching a designated section in a React application

useEffect(() => { console.log(window.scrollTo) console.log(textInput.current.offsetTop); }, [textInput,]) click here for more information check out the bottom of this page for a similar countdown feature - any ideas on how to implement it? ...

Tips on preserving type safety after compiling TypeScript to JavaScript

TS code : function myFunction(value:number) { console.log(value); } JS code, post-compilation: function myFunction(value) { console.log(value); } Are there methods to uphold type safety even after the conversion from TypeScript to JavaScript? ...

Next app unable to fetch cookie set by Express app

My project involves an app built on react/next and a server built on express. The process begins with a user authenticating via Github Oauth using passport.js, after which the server sends a connect.sid cookie. This cookie is crucial for rendering data to ...

Bring in a library exclusively for the backend to utilize in getInitialProps

My current setup In my project, I have implemented the use of getInitialProps in the _app.js file to pre-load data on the server side: import App from "next/app"; // The problematic import import nodeFetchCache from "node-fetch-cache" ...