skip to Main Content

I couldn’t find what is the problem or where should I look. I can send request with postman but my model file gives me this error
I have 2 file in my models documment user.js working well but product.js gives this kind of Error.

TypeError: Cannot read properties of undefined (reading ‘Product’)

import mongoose, { Schema, models } from "mongoose";

const productSchema = new Schema(
    {
        title: String,
        description: String,
        stock: Number,
    },
    {
        timestamps: true, 
    }
);
const Product = mongoose.models.Product || mongoose.model('Product', productSchema); //gives error at this line.

export default Product;

error page

I was trying to create a model for mongoDB. One of my model working well but other one not.

2

Answers


  1. try export const Product = model('Product', productSchema);
    use model

    Login or Signup to reply.
  2. The code below should work for you:

    import mongoose, { Schema } from "mongoose";
    
    const productSchema = new Schema(
        {
            title: String,
            description: String,
            stock: Number,
        },
        {
            timestamps: true, 
        }
    );
    
    export const Product = mongoose.model('Product', productSchema);
    

    Import this model when you want to use it:

    import { Product } from 'path/of/your/schema/'
    
    const product = await Product.create({
      title: "test",
      description: "test description",
      stock: "50",
    });
    
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search