reactjsmongodbmongoosenext.jsbackend

I am not able to create the document from next js app in mongoDB. Can any one tell me how to do this


This is my connectDB.js file

import mongoose from 'mongoose'



const connectDB = async () => {
  
  mongoose.connect(process.env.MONGO_URI)

};

export default connectDB;

This is my Product.model.js file

import mongoose from "mongoose";

const productSchema = new mongoose.Schema({
  title: { type: String, required: true },
  desc: { type: String, required: true },
  slug: { type: String, required: true },
  img: { type: String, required: true },
  category: { type: String, required: true },
  size: { type: String },
  color: { type: String },
  price: { type: Number, required: true },
  availableQty: { type: Number, required: true },
}, { timestamps: true })


export default mongoose.models.Product || mongoose.model("Product", productSchema)

This is /api/product.js file

import connectDB from "@/libs/connectDB"
import Product from "@/models/Product.model.js"




export default async function handler(req, res) {


  try {
    console.log("CONNECTING TO DB");
    await connectDB()
    console.log("CONNECTED TO DB");
    if (req.method === 'GET') {
      // const products = await Product.find()
      res.status(200).json({ d: "products" })
    }

    if (req.method === 'POST') {
      console.log("creating product")
      const product = await Product.create(req.body)
      console.log("created product")
      res.status(201).json({ product })
    }

    res.status(400).json({ error: 'Bad Request' })

  } catch (err) {
    console.log(err);
    res.status(500).json({ error: err })
  }

}

When I create a post request to /api/products with body I get this type of error:

MongooseError: Operation products.insertOne() buffering timed out after 10000ms at Timeout at listOnTimeout (node:internal/timers:573:17) at process.processTimers (node:internal/timers:514:7) error - unhandledRejection: Error [MongooseServerSelectionError]: connect ECONNREFUSED ::1:27017 at _handleConnectionErrors at NativeConnection.openUri { digest: undefined }


Solution

  • i think the error is because your connection good to the database is not establish in the right way i read the mongoose repo and they recommend this code to connect mongoose in nextjs and this connection code also will cache the data and this will help not keep sending request to the data base and this will make your app faster and more effective

    in your connectDB.js file just write this code

    import mongoose from 'mongoose'
    
    const MONGODB_URI = process.env.MONGO_URI
    
    mongoose.set('strictQuery', false);
    
    if (!MONGODB_URI) {
      throw new Error(
        'Please define the MONGODB_URI 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(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