Sergey Arenzon
Sergey Arenzon

Reputation: 325

Mongoose .find({}) returns empty array

My target is to fetch all documents in "Ingredients" collection but my code returns only empty array.

This is my "Ingredients" collection: enter image description here

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;

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;

Upvotes: 0

Views: 2350

Answers (3)

Kareem Abbas
Kareem Abbas

Reputation: 99

I've encountered the same error with next.js and after some debugging I found out that the issue with my code was that I should use await before the function that connects to the Database and then make the GET request after waiting for the connection to be done. I've attached some code below.

This the code fragment the caused the error at the begging:

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))
    }
}

and here is how I fixed it and it worked very well after that:

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

    await dbConnect() // just by adding 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))
    }
}

Upvotes: 0

Sergey Arenzon
Sergey Arenzon

Reputation: 325

OK just fixed it by creating new collection with the name "ingredient" (small letter case) and changed my scheme to this one and now it works.

Upvotes: 1

KShewengger
KShewengger

Reputation: 8269

Have it implement like this instead on some blocks of your code:

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



router.get('/', async (req, res) => {
    const ingredients = await Ingredients.find({});
    console.log(ingredients);
    
    res.json(ingredients);
})

Upvotes: 1

Related Questions