Converting Next.js with MongoDB to TypeScript

I recently set up a next.js application using the mongodb template:

npx create-next-app --e with-mongodb my-app

Additionally, I included TypeScript in my project. Now, I am faced with the task of converting /lib/mongodb.js to TypeScript.

Currently, the file looks like this with minimal type changes:

// lib/mongodb.ts

import { MongoClient } from 'mongodb'

const uri = process.env.MONGODB_URI
const options = {}

let client
let clientPromise: MongoClient

if (!process.env.MONGODB_URI) {
  throw new Error('Please add your Mongo URI to .env.local')
}
if (process.env.NODE_ENV === 'development') {
  if (!global._mongoClientPromise) {
    client = new MongoClient(uri, options)
    global._mongoClientPromise = client.connect()
  }
  clientPromise = global._mongoClientPromise
} else {
  client = new MongoClient(uri, options)
  clientPromise = client.connect()
}

export default clientPromise

However, I am encountering an error message: https://i.sstatic.net/8ssNc.png

Answer №1

I encountered a similar issue yesterday but managed to find a solution.

import { MongoClient } from "mongodb";

if (!process.env.MONGODB_URI) {
  throw new Error("Make sure to include your Mongo URI in the .env.local file.");
}

const uri: string = process.env.MONGODB_URI;
let client: MongoClient;
let clientPromise: Promise<MongoClient>;

if (process.env.NODE_ENV === "development") {
  // When in development mode, utilize a global variable to retain value during module reloads caused by HMR

  let globalWithMongoClientPromise = global as typeof globalThis & {
    _mongoClientPromise: Promise<MongoClient>;
  };

  if (!globalWithMongoClientPromise._mongoClientPromise) {
    client = new MongoClient(uri);
    globalWithMongoClientPromise._mongoClientPromise = client.connect();
  }

  clientPromise = globalWithMongoClientPromise._mongoClientPromise;
} else {
  // For production mode, avoid using global variables for best practices
  client = new MongoClient(uri);
  clientPromise = client.connect();
}

// Exporting a module-scoped MongoClient promise allows sharing across functions.
export default clientPromise;

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

NextJS Typescript Player

Encountering an issue during the build process, specifically with the error in audioRef.current.play(). The error message indicates that there is no play function available. I attempted to use an interface but it seems to not accept boolean values. Could ...

Running a JavaScript file from Docker to fill a MongoDB database is not working when using the WSL shell on Windows 10

I'm facing some issues while trying to populate my MongoDB using a script. Every time I run the script, I encounter errors even though the Docker container is up and running. For reference, I'm on Windows 10 using WSL shell. https://i.stack.img ...

Explore using partial keys for searching

I have a database collection structured as follows: { "_id" : ObjectId("56ec4e1bbf2f16a55f287d31"), "username" : "John Doe", "dates" : { "2014-12-24" : 25 }, } { "_id" : ObjectId("56ec4e1bbf2f16a55f287b32"), "username" ...

The Angular NgFor directive can only be used to bind data to Iterables like Arrays

I am encountering an issue when attempting to iterate through and display data using ngFor. The specific error appearing in the console is "Error: Cannot find a differ supporting object '[object Object]' of type 'object'. NgFor only su ...

Issue TS2307 encountered following the transition from Angular 11 to Angular 12 in a project migration

After upgrading my project from Angular 11 to Angular 12, I encountered errors while using the ng update command. Instead of troubleshooting further, I decided to take a more manual approach. I started by creating a brand new Angular 12 project, re-adding ...

Don't continue to expect other promises if one of them comes back with a special

I am dealing with a situation where I need to validate data in multiple tables by utilizing a function called validateTables(). This function relies on an asynchronous helper function queryTable() to check each table through API queries. The requirement fo ...

Exploring the capabilities of the Angular 2 expression parser alongside the functionality of the

Is there a way to create an equivalent of the Angular 1.x ngInit directive in Angular 2? I am familiar with the ngOnInit hook, which is recommended for initialization code. The ngInit directive seems like a quick and declarative way to prototype or fix a ...

Upon attempting to utilize Socket.io with Next.JS custom server, the server repeatedly restarts due to the error message "address already in

Every time I attempt to execute the refreshStock() function within an API endpoint /api/seller/deactivate, I encounter the following error: Error: listen EADDRINUSE: address already in use :::3000 at Server.setupListenHandle [as _listen2] (net.js:1318: ...

Updating image source on hover and mouse leave in React/Next.js

The Technologies I Utilize: Within my work, I use Next.js, Styled-Components, and Typescript. My Objective: My goal is to switch an image to a different one upon hovering over the parent div that contains it (the Card). The Solution I Have Implemented: ...

The type 'MutableRefObject<undefined>' cannot be assigned to the type 'LegacyRef<HTMLDivElement> | undefined'

I have created a customized hook that takes a ref object and observes its behavior: import { useState, useEffect, MutableRefObject } from "react"; const UseOnScreen = (ref: MutableRefObject<undefined>) => { const [isIntersecting, setI ...

Experiencing difficulty creating query files for the apollo-graphql client

I'm currently attempting to learn from the Apollo GraphQL tutorial but I've hit a roadblock while trying to set up the Apollo Client. Upon executing npm run codegen, which resolves to apollo client:codegen --target typescript --watch, I encounter ...

Sequencing animations with *ngIf in Angular 6

In my component, there are two elements that utilize the same fade animation. Only one element is visible on screen at a time, controlled by *ngIf directives for visibility management. The animation is a simple fade in/fade out effect. When the state of m ...

Creating a duplicate key in a JavaScript object that aligns with MongoDB's multiple search string rule: a step-by-step guide

I am attempting to utilize MongoDB for performing searches based on multiple search strings. Here is the format for executing a search with multiple strings in MongoDB: db.meals.find({ $and: [ { mealName: /fish/ }, { mealName: /rice/ }, { mealName: /spicy ...

What are some ways to conditionally implement dynamic imports?

Currently, I am working on a project that involves Reactjs + Nextjs. I am facing a situation where I need to dynamically import a component based on certain conditions. For example: const importMyComponent = isLiveBlog => ({ image: isLiveBlog ? i ...

What circumstances allow @Inject to be optional in Angular?

My Angular service is simple yet causing errors. Here's the code snippet: // service.ts export class SimpleService { // ... } // component.ts @Component({ selector: 'my-component', templateUrl: 'components/mycomp/mycomp.ht ...

Tips for updating div content when using dynamic content with EJS

I have created a blog using EJS and Node.js where the post content is stored in MongoDB as strings with HTML tags. However, when rendering the posts on the frontend, my current solution is replacing all div elements with the class of "blog_content" with th ...

Matching the Expected Type with Custom SWR Hook's Return Type

Currently, I am working on integrating swr into my project to create a custom block hook using generics. The goal is to have this hook creator accept mapParamsToKey and request methods as parameters and generate an SWR hook function. However, there seems t ...

Error: The use of options useCreateIndex and useFindAndModify is not compatible

Upon attempting to execute the code, I encountered an error message similar to the title. Here is my code: const URI = process.env.MONGODB_URL; mongoose.connect(URI, { useCreateIndex: true, useFindAndModify: false, useNewUrlParser: true, us ...

I am faced with a challenge involving an asynchronous function and the best approach to executing it synchronously

I devised the following plan: // Primary Function to Follow // Capture necessary local data // Transform into required editable format // Iterate through user's local images // Append image names to converted d ...

Please come back after signing up. The type 'Subscription' is lacking the specified attributes

Requesting response data from an Angular service: books: BookModel[] = []; constructor(private bookService: BookService) { } ngOnInit() { this.books = this.fetchBooks(); } fetchBooks(): BookModel[] { return this.bookService.getByCategoryId(1).s ...