In my E-commerce app built with Next.js and utilizing Mongoose, I defined a productSchema (models/Product) like this:
const mongoose = require("mongoose");
const productSchema = new mongoose.Schema(
{
title: { type: String, required: true },
slug: { type: String, required: true, unique: true },
desc: { 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 },
img: { type: String, required: true },
},
{ timestamps: true }
);
export default mongoose.model("Product", productSchema);
This is the getProducts API endpoint (api/getProducts):
import Product from "../../models/Product";
import connectDb from "../../middleware/mongoose";
const handler = async (req, res) => {
let products = await Product.find();
res.status.json({ products });
};
export default connectDb(handler);
This is the mongoose.js file defining database connection handling (middleware/mongoose):
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;
Upon opening the getProducts API endpoint in the browser, I encountered an error "TypeError: mongoose.model() is not a function." Any ideas on what could be causing this issue and how to resolve it?