Home > OS >  Mongoose find() returns empty array
Mongoose find() returns empty array

Time:12-31

I am trying to find a certain collection which I see existing in my mongoDB database however trying to access it through my express server used to work but it does not work anymore. The connection to the database is successful.

I searched through SO and found all kinds of solutions about the naming of my models, however non of it worked for me. Tried all bunch of stuff but I still get an empty array as response.

Pokemon.js

This is my route which searches for Pokemon in my database and should return it to my client. The output of the console log shows an empty array. LOG: Pokemon fetched from DB: []

import Pokemon from "../models/pokemon.model.js";
import express from "express";
const router = express.Router();

// get all pokemon
router.route("/").get(async (req, res) => {
  try {
    const pokemon = await Pokemon.find();
    console.log(`LOG: Pokemon fetched from DB: ${JSON.stringify(pokemon)}`);
    res.json(pokemon);
  } catch (err) {
    console.log(err);
  }
});

export { router };

Pokemon.model.js

My collection on mongoDB is called pokemons

import mongoose from "mongoose";

const Schema = mongoose.Schema;

const pokemonSchema = new Schema(
  {
    pokemon: { type: Array, required: true },
  },
  {
    timestamps: true,
  },
  { collection: "pokemons" }
);

const Pokemon = mongoose.model("Pokemon", pokemonSchema, "pokemons");
export default Pokemon;

And this is how I send the request to fetch the data in my client using React.js My server runs locally with port 5000.

      try {
        fetch(`http://localhost:5000/pokemon`)
          .then((response) => response.json())
          .then((allpokemon) => {
            let list = allpokemon[0]?.pokemon;
            setPokemonList([...pokemonList, list]);
          });
      } catch (err) {
        console.warn(err);
      }

CodePudding user response:

Found the issue eventually, the code provided is okay and is not the issue. The issue is in the way I have connected to the server which was as the following

ATLAS_URI="mongodb srv://<credentials>@cluster0.0qxv0.mongodb.net/?retryWrites=true&w=majority"

Since I have not defined the name of the database before the query params, I assume it did not know to point to the correct database. I guess it used to work like that before since I had only one database in my cluster but at some point I somehow made a test database and from this point on it did not work.

So the solution was as the following

ATLAS_URI="mongodb srv://<credentials>@cluster0.0qxv0.mongodb.net/<database_name>?retryWrites=true&w=majority"

After I added my database name where <database_name> is positioned in the URI I could access the data in my database collections again.

CodePudding user response:

I wanted to do same and i write this code and this worked for me Note- at the time of API Testing use raw-data instead of form-data - set Content-type application/json in Postman

import * as mongodb from 'mongodb'; //use Require if you use ES5 express
import { MongoClient } from 'mongodb'

router.post('/api/fetchPokemon', (req, res) => {

  MongoClient.connect("mongodb://localhost:27017/databaseName",(err, db) => {

    var userDetails = req.body;

    if (err) throw err;

    var dbo = db.db("databaseName");

    const query = {
      email: userDetails.email,
      password: userDetails.password
    }; //here you can set your Array
      // use fineMany if you want multiple array 
    dbo.collection("CollectionName").findOne(query, (err, result) => {
      // now you can use this result according to your need
      if (err) throw err;

      console.log(result);

      res.json(result);

      db.close();
    });
  });
});
  • Related