I'm having trouble connecting MongoDB with Mongoose in Next.js 13.3 Version. I keep getting errors when trying to import the connectDb file or UserSchema file in api/getProducts/route.js file. Can someone please help me with step-by-step instructions on how to make this connection? I'm completely stuck!
First, I created a mongoose.js file in a folder named middleware:
import mongoose from "mongoose";
const connectDb = (handler) => async (req, res) => {
if (mongoose.connections[0].readyState) {
return handler(req, res);
}
await mongoose.connect(process.env.MONGO_URI);
return handler(req, res);
};
export default connectDb;
Next, I defined the User schema in models/User.js like this:
const mongoose = require("mongoose");
const UserSchema = new mongoose.Schema(
{
name: { type: String, required: true },
email: { type: String, required: true, unique: true },
password: { type: String, required: true },
},
{ timestamps: true }
);
mongoose.models = {};
export default mongoose.model("User", UserSchema);
However, whenever I try to import either connectDb or User schema in the api/getProducts/route.js file, I encounter errors:
import connectDb from "../../../middleware/mongoose";
export async function GET(request) {
return new Response("Hello, Next.js!");
}