How to connect MongoDB with Next JS Using Mongoose


How to connect MongoDB with Next JS Using Mongoose

Next JS


  1. If you're building a web application with Next.js and using MongoDB as your database, connecting the two can seem daunting. However, with the help of Mongoose, a popular MongoDB object modeling tool, the process can be made much simpler. In this tutorial, we'll walk through the steps required to connect MongoDB with Next.js using Mongoose.
    1. download mongodb compass
    2. npm install mongoose
    3. Create config and models directory
    4. Add MongoDb Path in next.config.js
         const nextConfig = {
           env: {
             MONGODB_URI: "mongodb",
    5. Inside config create dbConnect.js Write following code inside dbConnect.js
                         import mongoose from 'mongoose'
                       const MONGODB_URI = process.env.MONGODB_URI
                       if (!MONGODB_URI) {
                         throw new Error(
                           'Please define the MONGODB_URI environment'
                       let cached = global.mongoose
                       if (!cached) {
                         cached = global.mongoose = { conn: null, promise: null }
                       async function dbConnect() {
                         if (cached.conn) {
                           return cached.conn
                         if (!cached.promise) {
                           const opts = {
                             bufferCommands: false,
                           cached.promise = mongoose.connect(MONGODB_URI, opts).then((mongoose) => {
                             return mongoose
                         try {
                           cached.conn = await cached.promise
                         } catch (e) {
                           cached.promise = null
                           throw e
                         return cached.conn
                       export default dbConnect
    6. Inside Models create file user.js with following code
                 import mongoose, { model } from "mongoose";
                 const userSchema = new mongoose.Schema({
                   name: String,
                   email: String,
                   password: String,
                 export default mongoose.models.User || mongoose.model("User", userSchema);
    7. Inside src\pages\api create a directory user
    8. Inside user directory create index.js with following code
               import User from "../../../../models/User";
               import dbConnect from "../../../../config/dbConnect";
               export default async (req, res) => {
                 const { method } = req;
                 switch (method) {
                   case "GET":
                     try {
                       const user = await User.find({}).sort({ _id: -1 });
                       res.status(200).json({ success: true, data: user });
                     } catch (error) {
                       res.status(400).json({ success: false });
                     res.status(400).json({ success: false });
    9. Insert some documents inside MongoDB
    10 Visit URL http://localhost:3000/api/user to get user list as API from MongoDB

Watch How to connect MongoDB with Next JS Using Mongoose Installation

Related Projects

Recent Comments

Latest Comments section by users