1

Can someone help me with this problem, mongoose not fetching any data from MongoDB atlas? Everything is fine and I am able to fetch data from cmd, but with mongoose, it returns an empty array.

const express = require('express');
const cors = require('cors');
const mongoose = require('mongoose');

const app = express()
app.use(express.json())
app.use(express.urlencoded())
app.use(cors())
const dotenv = require('dotenv');
dotenv.config()

mongoose.connect(process.env.DB_ACCESS, () => {
    console.log("db connected successfully..")
})

const hospitalTemplate = new mongoose.Schema({
    state: {
        type: String,
        required: true
    },
    city: {
        type: String,
        required: true
    },
    hospitalname: {
        type: String,
        required: true
    },
    mobilenumber: {
        type: Number,
        required: true
    },
    image1url: {
        type: String,
        required: true
    },
    rating: {
        type: Number,
        required: true
    },
    availablebeds: {
        type: Number,
        required: true
    }
})

const Hospital = new mongoose.model('Hospital', hospitalTemplate)

// // Routes
app.get("/search", async (req, res)=> {
    await Hospital.find({}, (err, data)=> {
        if (data) {
            res.send(data);
            console.log(data)
        } else {
            res.send({ message: "data problem" });
            console.log("data problem");
        }
    }).clone().catch(function(err){ console.log(err)})
})
app.listen(4000,() => {
    console.log("server is running")
})

After running this program, I get an empty array when I visit "localhost:4000/search"

yogesh kumar
  • 103
  • 10
  • Make sure you're successfully being connected to the database. [Check this answer](https://stackoverflow.com/a/19606067/11801683) – jewishmoses Dec 18 '21 at 08:33
  • yes, I am connected, it shows me "db connected successfully.." everytime I run the program – yogesh kumar Dec 18 '21 at 17:11
  • No, "db connected successfully" will always get printed, even if the connection failed. Make sure you are connected to the DB by printing `console.log(mongoose.connection.readyState);` and checking that is equal to 1. – jewishmoses Dec 18 '21 at 17:51

0 Answers0