Guide to setting up Mongodb with mongoose in the latest Next.js 13.3 update

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!");
}

Answer №1

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

export const FETCH = initializeDatabase(async(request) => {
  return new Response("Welcome to the world of Next.js!");
})

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Exploring the capabilities of asynchronous middleware using Mongoose

Implementing a 'save' middleware in Mongoose to log activity in the DB when an action is taken. Here's an example: UserSchema.post("save", function (doc) { mongoose.model("Activity").create({activity: "User created: " + doc._id}); }); ...

Retrieve information from an array within a blockchain smart contract

My smart contract factory has the ability to deploy another smart contract. Within the factory contract, there is a specific function: address[] public migrations; ... function getMigrations() public view returns (address[] memory) { return migr ...

Internet Explorer problem with menu hover

Website: I am encountering an issue with Internet Explorer (9 or lower) where, on hovering over any menu item on the homepage and attempting to select items beyond the first one - for example, hovering over "Shop" and then trying to click on "Brushes" or ...

Reactjs encountered a problem with the click event

I seem to be facing a small issue with my react component code. I can't seem to figure out what's wrong. Here's the component code: import React, { Component, PropTypes } from 'react'; import styles from './Menu.css'; im ...

Remove the dropdown menu in real time, ensuring that only the most recent one is

Although the example may seem unusual, I am deliberately recreating a real problem to find a solution. When I click on a button, it generates 3 dynamic dropdowns based on a list of animals. My issue is that I want to delete a selected item, but it always ...

Mongoose Query: How to populate nested fields two levels deep in MongoDB without populating the first level fields?

Here is the outline of my Mongoose Schema: var SchemaA = new Schema({ field1: String, ....... fieldB : { type: Schema.Types.ObjectId, ref: 'SchemaB' } }); var SchemaB = new Schema({ field1: String, ....... fieldC : { type: Schema.Ty ...

Analyzing the structure according to the month/week/year

My array consists of count and date values: day = [ { count: 1, date: '2022-07-07' }, { count: 1, date: '2022-08-14' }, { count: 2, date: '2022-07-19' }, { count: 4, date: '2022-07-19' }, { count: 2, date: ...

"Encountering a problem with jQuery AJAX - receiving an error message despite the status code being

Attempting to make a jQuery Ajax request using the following code: $.ajax({ url: '<MY_URL>', type: 'POST', contentType: 'application/json;charset=UTF-8', data: JSON.stringify(data), dataType: 'a ...

Discover the power of utilizing JavaScript to sort through table rows by filtering them based on the selections of multiple checkbox

How can I create interdependent logic for checkbox sections in a form to filter based on all selections? I am looking for help with my code snippet that showcases checkboxes controlling the visibility of table rows: $(document).ready(function() { $(" ...

Adjust the width of a textarea dynamically as you type by detecting keyup events

Two text areas have the same text formatting. Their IDs are textareaA and textareaB. I've successfully added functionality to resize textareaA on keyup. How can I make textareaB resize its WIDTH while the user is typing in textareaA? Here's wha ...

Looping Feature in Ionic Framework's Slides Component

Currently, I am working on developing an application using Ionic-Angular. When it comes to incorporating slides in my app, I opted for the ionic 4 ion-slides component. Everything was going smoothly until I wanted to enable looping for the slides so that u ...

Lifting Formik's "dirty" value/state to the parent component: A step-by-step guide

Parent Component const Mother = () => { const [dusty, setDusty] = useState(false) return ( <ChildComponent setDusty={setDusty} /> ) } Child.js ... <Formik initialValues={initialValues} onSubmit={onSubmitHandler} validationSchema={sch ...

locate the presence of a specific letter within a sequence of characters

When dealing with strings like "Galley1", "Galley2", "Galley3", "Galley4", "Galley5", "Galley6" up to "Galley20", the task is to determine whether a condition is met. The condition should return true if the string contains a number between 1 and 7, inclusi ...

Is there an issue with .addClass not working on imported HTML from .load in jQuery?

I have set up a navigation bar that hides when the user scrolls down and reappears when they scroll up. I want to keep the navbar code in a separate HTML file for easier editing. .load In the index.html file, the navbar code is included like this: <di ...

Encountering an issue with the mongo command following the installation of MongoDB version 3.6.3

After successfully installing MongoDB version 3.6.3, I encountered issues when trying to run the Mongo command. Upon running the command, I received the following error message: MongoDB shell version v3.6.3 connecting to: mongodb://127.0.0.1:27017 ...

How to handle and display validation errors in an AJAX post request using express-validator in Node.js/Express

I am in the learning phase with Node and attempting to display validation errors (using express-validator and express 4) when a user submits a form. The validator appears to be functioning properly because when I log the data to the console, everything lo ...

Comparing "this" and $scope within the context of Angular

I have gone through similar questions and their answers, but I am still struggling to understand this. Any assistance on this would be greatly appreciated. The code snippet below functions correctly. However, if I substitute $scope with this before the bi ...

Animating avatars with Three.js

Seeking some guidance on utilizing the three.js library for creating animations. Specifically, I am interested in animating an avatar that has been exported from Blender to Collada format (.dae), to move an arm or a leg. I would like to achieve this anim ...

The functionality of Jquery appears to be malfunctioning on the Drupal platform, although it performs

I've built a jQuery carousel that is fully functional when tested locally, but encounters issues when uploaded to a Drupal platform. Surprisingly, the jQuery functions properly when entered through the Console. Here's the jQuery code: carousel = ...

Struggling to figure out how to properly shuffle my deck of cards array in JavaScript. Can't seem to grasp how to pass the array correctly

Currently, I am engrossed in my personal project and watching tutorials just for the fun of it. My goal is to create a game for my school project which is inspired by a war card game that I used to play as a child - where the highest number wins. I have ...