When using `Mongoose.find({})`, the result is an empty array

I'm having issues with my code where it's only returning an empty array when I try to fetch documents from the "Ingredients" collection.

Here is a link to my "Ingredients" collection image: https://i.stack.imgur.com/Gpw8V.png

Below is the ingredient model file:

const mongoose = require('mongoose');

const Schema = mongoose.Schema;


const ingredientSchema = new Schema({
    name: String,
    number: Number
})

const Ingredient = mongoose.model('Ingredients', ingredientSchema);

module.exports = Ingredient;

And here is the ingredients route file:

const router = require('express').Router();
let Ingredients = require('../models/ingredients.model');

router.route('/').get((req, res) => {

    let getIngredients = async function (){
        let ingredients = await Ingredients.find({});
        console.log(ingredients);
        res.json(ingredients)
    }
    getIngredients()
})

module.exports = router;

Answer №1

You can incorporate it in this way within certain sections of your code:

const { Router } = require('express');
const newRouter = new Router();



newRouter.get('/', async (req, res) => {
    const items = await Items.find({});
    console.log(items);
    
    res.json(items);
})

Answer №2

I was able to resolve the issue by setting up a new collection called "ingredient" in lowercase and updating my schema accordingly. This adjustment has successfully resolved the problem.

Answer №3

While working with next.js, I ran into a similar issue and after some troubleshooting, I discovered that the problem stemmed from not using await before connecting to the Database function. By adding this small adjustment and allowing the connection to be established before making the GET request, I was able to resolve the error. Below is a snippet of the code:

Initially, this snippet triggered the error:

export default async function handler(req, res) {
    const { method } = req;

    dbConnect() // the function that connects to the database

    if(method === "GET") {
        await Trip.find()
        .then(trips => res.json(trips))
        .catch(error => res.status(500).json(error.message))
    }
}

After implementing the fix, the code worked smoothly:

export default async function handler(req, res) {
    const { method } = req;

    await dbConnect() // simply added 'await' before connecting to the database

    if(method === "GET") {
        await Trip.find()
        .then(trips => res.json(trips))
        .catch(error => res.status(500).json(error.message))
    }
}

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

Tips for silencing outdated npm warnings in bash

On my Linux Mint 18.0 system, I have multiple versions of node.js installed and manage them using nvm. Due to a project requirement, I need version 0.10 to be the default (nvm use 0.10). However, every time I open my terminal, I receive the following warni ...

Running res.render in an asynchronous manner within an express application

My goal is to make this router respond asynchronously: var express = require('express'), router = express.Router(); router.get('/', function(req, res, next) { res.render('contact', { titleShown: true, title: & ...

The fetch() POST request is met with an error message stating "415 Unsupported Media Type"

I keep encountering a 415 error when attempting to upload a PDF file using fetch(). The PDF file resides in the same directory as the js file, and the name is correct. async function uploadFile(filePath, extension, timestamp) { const url = "https ...

Issue: The node.js version installed on this system lacks the necessary openssl crypto support for

I am relatively new to working with node.js and have been attempting to set up a basic websockets server. However, I am encountering an issue when trying to run an example server. The error message reads: "Error: node.js not compiled with openssl crypto su ...

Utilizing Express JS to make 2 separate GET requests

I am facing a strange issue with my Express API created using Typescript. The problem revolves around one specific endpoint called Offers. While performing operations like findByStatus and CRUD operations on this endpoint, I encountered unexpected behavior ...

Sending updates to the client as soon as a database field is modified

I am currently utilizing socket.io to transmit data from my database to the client. However, my current code sends data to the client every second, even when the data remains unchanged. Is there a way for me to only send data when a field in the database h ...

"Discovering Multiple Documents in MongoDB: A Step-by-Step

How can I retrieve multiple documents at once in MongoDB? In my post method, I have a collection called appointments. When receiving post data, I need to check if they already exist in the database using hour_response and date_response. However, I'm ...

Guide on how to modify a static css file using Node.js

Issue Whenever a user updates the theme on the front-end, my Node.js API needs to update the static CSS file located in a public folder set up by Express. This way, when pages are served again with <link href="public/theme.[userId].[hash].css", the use ...

Tips for passing a page as an argument in the function parameter of the page.evaluate() method?

I keep running into this issue when I pass the page as an argument: TypeError: Converting circular structure to JSON --> commencing at object with constructor 'BrowserContext' | property '_browser' -> object with const ...

The React Component in Next.js does not come equipped with CSS Module functionality

I have been attempting to incorporate and apply CSS styles from a module to a React component, but the styles are not being applied, and the CSS is not being included at all. Here is the current code snippet: ./components/Toolbar.tsx import styles from & ...

Utilizing JSON Data to Display Charts in a React Application

I'm facing an issue while trying to visualize JSON data in a graph. It seems to be throwing errors, and I'm unsure of what needs to be changed. Any insights on this would be greatly appreciated. Thank you! The JSON data structure is quite straigh ...

What is the process for initiating a local Lambda edge viewer request?

Is there a way to run aws cloudfront lambda edge functions locally and simulate the event in order to observe the response from one of the four functions? I made modifications to the viewerRequest function of lambdaEdge, but I'm wondering if there is ...

What is the best method for setting up an undetected-chromedriver in NodeJs?

Looking for help with using undetected chrome driver in NodeJS. I found a python library but want to code in NodeJs and use this library to target the browser. https://github.com/ultrafunkamsterdam/undetected-chromedriver I tried placing the undetected-ch ...

Gulp ceased to function following the upgrade to node.js version 4.1

Recently, I made the leap from node 0.12.x to version 4.1.0. However, I encountered an issue after updating - my beloved gulp stopped working. A puzzling error message popped up in the console upon attempting to run gulp: module.js:338 throw err; ^ Error ...

What is preventing me from defining an alias @bundled-es-modules/chai for chai?

When working with NPM, you have the option to install a package under an alias, like this: npm i alias@npm:real-package-name To learn more about this aliasing feature, check out the announcement here: b7b54f2d1 413 #3 530 Add support for package aliase ...

Using a single package manager for both backend and frontend development - is it possible? (Yarn/NPM)

Before, I relied on NPM for server-side tasks and Bower for frontend. NPM would install packages in the node_modules/ directory, while a .bowerrc file directed package installations to public/lib. Recently, I've made the switch to Yarn from NPM, and ...

The system does not acknowledge 'grunt'

I am a beginner when it comes to working with grunt and currently using: Node: 6.9.2 npm: 3.10.9 Operating System: Windows 7 Every time I attempt to install grunt by running the command below: npm install -g grunt-cli An error message pops up saying: ...

Tips on excluding null or empty values when writing to JSON with NodeJS

When saving the following content to a JSON file, I want to exclude any fields with a value of null or blank. Specifically, I do not want to include productPrice and productRating fields in the JSON file. Since I am not very familiar with NodeJS, can someo ...

Develop a NodeJS application that utilizes Quickbooks OAuth 2.0 for seamless integration and persistent login functionality

I successfully integrated a NodeJS application with my QuickBooks developer account using OAuth2.0. With the client key and secret key, I can obtain the access token by signing in to QuickBooks, allowing users to send invoices or retrieve data from their a ...

I'm encountering a strange issue where Node JS is mistakenly claiming that the method doesn't exist, even though

Ah, it seems I've encountered an error in my test project. The issue lies with Node JS not being able to locate the getStr function within the Another object. Allow me to share the code with you: test.js var Another = require('./another.js&apo ...