I am encountering an issue in Nextjs with mongoose where it seems that the function mongoose.model() is not

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?

Answer №1

I noticed a duplication of field names, both named "title," within the schema. To resolve this issue and ensure the program runs smoothly, consider renaming one of the fields to eliminate redundancy in the schema structure. After making this adjustment and running the model file again as per my suggestion, I was able to successfully run it without encountering any errors.

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

Telegram: verification key mismatch detected

I am currently facing an issue with implementing a Telegram PHP example using JavaScript. The hashes do not match, even after running the example's php code which also resulted in failure with identical hashes. I have tried adjusting my bot settings b ...

Spinning a 3D shape on its y-axis using three.js

Recently I delved into the world of three.js and came across an interesting project that I am trying to tweak. I am curious to find out if there is a way to make the globe object rotate around its y-axis with minimal changes to the existing code, or if a ...

Singling out a particular navigation tab

When attempting to link specific table IDs so that the corresponding tab is active when opened (i.e. www.gohome.com/html#profile), I am facing an issue where the active tab remains unchanged. Even after specifically calling out tab IDs, there seems to be n ...

Tips for handling Redux state when a user lands on a product details page without navigating through the application

Currently, I'm tackling a challenge in my Redux application that has left me uncertain about the best approach to take. Imagine I have a page called ProductsList located at example.com/products On this page, I trigger the getProducts redux action wh ...

Modify the appearance of selectInput and numericInput controls

Looking to update the appearance of my Shiny UI elements to better match the overall website design. Specifically, I want to eliminate the rounded edges on the selectInput boxes for a cleaner look like this: https://i.sstatic.net/pepak.png Additionally, ...

How can you show a green check mark next to an input field in AngularJS after inputting valid data?

I am diving into the world of AngularJS and Angular Material with my web application. As a beginner in AngularJS and Angular Material, I need some help. My current task is to display a green checkmark next to an input field only when valid data is entere ...

Is there a way to locate and refine the blogs associated with a specific user?

Check out the following blog entries stored in the Database: [ { _id: 5fec92292bbb2c32acc0093c, title: 'Boxing ring', author: 'T. Wally', content: 'boxing stuff', likes: 0, user: { _id: 5fd90181 ...

``Is there a way to refresh the CSS, button, or a specific part of a webpage after a GET request has been

Upon receiving a GET request, the values appear and the button disappears. View image here. The button functions properly on localhost. See it in action here. I'm attempting to incorporate a Facebook share button on a page with dynamic content like ...

Manipulate the value of an HTML element's style parameter with jQuery

How do I change an element's style property using jQuery? This is the HTML code I am working with: <div id="template" style="width:200px; height:200px; border:none;">blabla...</div> I attempted to do this: $('#template').attr ...

I am having trouble retrieving the content-length from the response headers within the app.use() middleware function

Can anyone help with retrieving the content-length from response headers within the app.use() middleware function? const app = express(); app.use((req, res, next) => { // Need to find a way to access content-length of res console.log("co ...

Choosing specific anchors based on their corresponding div ids

Just beginning my journey with JS, looking to tackle an issue (I know, everyone says that!). My task is to create a script that can choose an anchor element and inject an <img>. Nested within a div with the id of _nwa_social_logins, there are multipl ...

Modifying element size using jQuery causes issues with maintaining a 100% height

I am facing an issue with a sidebar that is styled using the following css properties: background:#164272; position:absolute; left:0px; top:70px; width:250px; height:100%; When I use jQuery to display a table that is initially hidden and on ...

What is the amount of memory consumed by a string data type?

Just a quick query - how much data (in bytes) do strings occupy? Does each character in a string take up one byte? I attempted to look it up, but unfortunately ws schools didn't provide an answer... I'm curious about this as I'm looking to ...

Node.js Mongoose repeatedly inserts the same individual element instead of all elements

After running the code below, I noticed that while the value printed at the console.log appears to be correct, all the objects in the database end up with the same hex and image path, even though their ids are different. I initially tried using findOne, ...

Unable to find module reference "three" at 137

Returning to an older project, I realized that nothing was loading. When I checked the console log, this is what I found: Uncaught TypeError: Failed to resolve module specifier "three". Relative references must start with either "/", "./", or "../". In my ...

MongoTemplate's Criteria for matching all documents

I recently noticed that in Mongosh I am able to use an empty object {} to match all documents. However, when trying to achieve the same thing using Java MongoTemplate API, I couldn't find an equivalent method. The closest solution I came up with is: Q ...

Javascript function always runs last despite being called first

I am facing a situation where I have two functions associated with the Vue object named "form": form.sizeChartAsImage(); form.setSizeChart(); The code for these functions is as follows: setSizeChart: function () { for (i = 0; i < this.col ...

Arrange links in a list using Protractor and select one to click at random

How can I create a list of all 100 search engine result weblinks and then use a random number generator to click on one randomly? Here is the code I've been working with that doesn't seem to be functioning properly: for (var iterate=1; iterate& ...

What is the best way to import and export modules in Node.js when the module names and directories are given as strings?

Here is the structure of my folder: modules module-and index.js module-not index.js module-or index.js module-xor index.js moduleBundler.js The file I'm currently working on, moduleBundler.js, is re ...

Comparing querySelectorAll, NodeIterator, and TreeWalker: which is the quickest JavaScript DOM iterator?

Is there a way to transform a DOM tree into an Array, with the root being the first element? I'm looking for a solution using plain JavaScript. What is the most efficient method to accomplish this? Here is an example of the HTML structure: <div cl ...