umair mohsin

umair mohsin

  • 1.4k
  • 387
  • 65.6k

can't insert data using  mongoose

Jul 20 2024 3:56 PM

can't inset data using  mongoose.here are the details.i am working in seperate directories

middleware.js code

import mongoose from "mongoose";
const connectDB=handler=> async(req,res)=>{
    if(mongoose.connections[0].readyState){  //if already connection exist
 return handler(req,res)
    }
    await mongoose.connect(process.env.MONGO_URI)
    return handler(req,res)
}
export default connectDB;

Product Model Schema

const mongoose = require('mongoose');
 main().catch(err => console.log(err));
const ProductSchema = new mongoose.Schema({
    title:{type:String,required:true},
    slug:{type:String,required:true,unique:true},
    desc:{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},
    qtyInStocks:{type:Number,required:true},
  },{timestamps:true});
  mongoose.models={};
export default  mongoose.model("Product",ProductSchema);

addproductapi code

import Product from "../../../models/Product";
import connectDB from "../../../middleware/mongoose";
 const handler= async (req, res)=> {
    if(req.method=='POST'){
        for (let i = 0; i < req.body.lenght; i++) {
            let p=new Product({
                title:req.body[i].title,
                slug:req.body[i].slug,
                desc:req.body[i].desc,
                img:req.body[i].img,
                category:req.body[i].category,
                size:req.body[i].size,
                color:req.body[i].color,
                price:req.body[i].price,
                qtyInStocks:req.body[i].qtyInStocks
            });
            await p.save();
        }
        res.status(200).json({success:"Success"});  
    }
    else{
        res.status(400).json({error:"this method is not allowed"});  
    }
  }
  export default connectDB(handler)

get product api code

import Product from "../../../models/Product";
import connectDB from "../../../middleware/mongoose";
 const handler= async (req, res)=> {
    let products= await Product.find();
    res.status(200).json({products});
  }

  export default connectDB(handler) //if our application not connected to db this line will connect us

Note: this code is creating database in mongodb compass with name products, addproducts api is working fine because thunder client returns status 200.   Getproduct is returning 304 why I don’t know. i have check my code twice,thrice even i restart my server many times.

help me out please


Answers (1)