Mongo connection error with next.js

Why do I keep getting this error when I run my dbConnect() function?

This is how I’m calling the dbConnect function

import Users from "../../../api/models/Users";
import axios from "axios";
import dbConnect from "../../util/mongodb";

const handler = async (req, res) => {
    const { method } = req;
    await dbConnect();

    switch (method) {
        case "GET":
            try {
                const res = await Users.find();
                res.status(200).json(res);
            } catch (error) {
                res.status(500).json(error);
            }

            break;
        case "POST":
            console.log(POST);
            break;
        case "PUT":
            console.log(PUT);
            break;
        case "Delete":
            console.log(Delete);
            break;
    }
};

export default handler;

And this is where i create the function util/mongodb.js

import mongoose from 'mongoose'

const MONGO_URL = process.env.MONGO_URL

if (!MONGO_URL) {
  throw new Error(
    'Please define the MONGO_URL environment variable inside .env.local'
  )
}

/**
 * Global is used here to maintain a cached connection across hot reloads
 * in development. This prevents connections growing exponentially
 * during API Route usage.
 */
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(MONGO_URL, opts).then((mongoose) => {
      return mongoose
    })
  }
  cached.conn = await cached.promise
  return cached.conn
}

export default dbConnect

what am I doing wrong? I’ve been on this for days!

This topic was automatically closed after 180 days. New replies are no longer allowed.