Home > OS >  Mongoose is returning empty array while fetching data from MongoDb Atlas. Why?
Mongoose is returning empty array while fetching data from MongoDb Atlas. Why?

Time:08-11

App.js file->Connection is established successfully, but in find() callback,data is empty[]

    const express = require('express');
    const mongoose = require('mongoose');
    const Users = require('./users');
    const app = express();
    mongoose.connect("mongodb srv://sanjeev:**pass**@cluster0.ckywrym.mongodb.net?retryWrites=true&w=majority/sanjeevDb",
        {
            useNewUrlParser: true,
            useUnifiedTopology: true,
        }).then(() => console.log("connection established successfully"));

Within find callback I am getting empty array in data

    Users.find({}, (error, data) => {
        if (error)
            console.log("Error: ", error);
            console.log(data)
         });

users.js - defining the schema as same on mongoDb Atlas

    const mongoose = require('mongoose');
    let userSchema = new mongoose.Schema({
        _id: mongoose.Schema.Types.ObjectId,
        name: String,
        email: String,
        country: String
    });
    
    module.exports= mongoose.model('userCollect', userSchema);

enter image description here

CodePudding user response:

You are using the callback function so, all callbacks in the Mongoose use the pattern callback(err, data). So, if an error occurs while executing the query the error parameters will contain the error document and the data will be null. Your If condition looks like this:

if (error)
    console.log("Error: ", error);
    console.log(data)
});

This means data will show in the console if there is an error because your data is inside the if block. so, you need to write data in the else block something like this:

  if (error) {
     console.log("Error: ", error);
    }
     else {
        console.log(data)
     }
   }):

CodePudding user response:

you are logging data even when there is error. do this

Users.find({}, (err, data) => { 
if (err){
console.log(err);
} else {
console.log(data);
})

or

//with async (recommended)
try {
const users = await Users.find({});
console.log(users);
} catch (err) {
console.log(err);
}
  • Related