Open In App

How To Set Up Mongoose With Typescript In NextJS ?

Last Updated : 30 Jun, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Share
Report
News Follow

Integrating Mongoose with TypeScript in a Next.js application allows you to harness the power of MongoDB while maintaining strong typing and modern JavaScript features. This guide will walk you through the process of setting up Mongoose with TypeScript in a Next.js project, ensuring your application is robust, scalable, and easy to maintain.

Prerequisites:

Steps to Create a NextJS App and Installing Module

Step 1: Initialize Next app and move to the project directory.

npx create-next-app my-next-app
cd my-next-app

Step 2: Install the required dependencies:

npm install tailwindcss  react-hook-form mongoose mongodb

Project Structure

Screenshot-2024-05-30-141047
Project Structure

Step 3: Setting Up MongoDB Connection inside .env file add:

MONGOB_URI = mongodb+srv://yourMongodbnab:yourpassword@cluster0.ldnz1.mongodb.net/DatabaseName

The Updated dependencies of your package.json file will look like this:

"dependencies": {
"mongoose": "^8.4.0",
"next": "13.4",
"react": "^18",
"react-dom": "^18"
}

Example: Beow is an example of uploading an Image to MongoDB using only NextJS 13.4.

JavaScript
// utils/connectToDb.ts
import mongoose, { Connection } from "mongoose";
import { GridFSBucket } from "mongodb";

let client: Connection | null = null;
let bucket: GridFSBucket | null = null;

const MONGODB_URI = process.env.MONGODB_URI as string;

interface DbConnection {
    client: Connection;
    bucket: GridFSBucket;
}

async function connectToDb(): Promise<DbConnection> {
    if (client) {
        return { client, bucket: bucket as GridFSBucket };
    }

    await mongoose.connect(MONGODB_URI);

    client = mongoose.connection;
    bucket = new mongoose.mongo.GridFSBucket(client.db, {
        bucketName: "images",
    });

    console.log("Connected to the Database");
    return { client, bucket };
}

export default connectToDb;
JavaScript JavaScript JavaScript JavaScript

Start your Next.js development server:

npm run dev

Visit http://localhost:3000 in your browser to see the application in action.

Output:

Screenshot-2024-05-21-142353
Output

When you enter the file name, upload a file, and then click on the submit button, your file is successfully uploaded to MongoDB.

Conclusion

Overall, using Mongoose in Next.js empowers developers to build feature-rich, data-driven web applications with a modern frontend and a robust backend database, enabling seamless integration, efficient data management, and scalable architecture.


Next Article

Similar Reads

three90RightbarBannerImg