简体   繁体   中英

How to connect Mongodb with mongoose in current Next.js 13.3 Version?

I am trying to connect mongodb with the help of mongoose in Next.js 13.3 Version but it is giving different errors when i import the connectDb file or UserSchema file in api/getProducts/route.js file. Please Help and tell step wise how to connect I am stuck!

First I have created 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;

Then I have made Schema of user like this in models/User.js:

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);

But when in api/getProducts/route.js file when importing whether connectDb or User schema gives error:

import connectDb from "../../../middleware/mongoose";

export async function GET(request) {
  return new Response("Hello, Next.js!");
}
import connectDb from "../../../middleware/mongoose";

export const GET = connectDb(async(request) => {
  return new Response("Hello, Next.js!");
})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM