skip to Main Content

I followed a tutorial, connected to mongoDB via mongoose, but for some reason the console.log(data) doesn’t show anything.

const mongoose = require('mongoose');
const mongoURI = 'mongodb+srv://gofood:[email protected]/?retryWrites=true&w=majority'

process.on('uncaughtException', err => {
  console.log('UNCAUGHT EXCEPTION! 💥 Shutting down...');
  console.log(err.name, err.message);
  process.exit(1);
});

async function called(){
  console.log('Connection successful!');
  const fetched_data = await mongoose.connection.db.collection("foodCategory");
  console.log('reaching here?????')
  fetched_data.find({}).toArray(function(err, data){
    if(err) console.log(err);
    else console.log(data);})
};

const mongoDB = async () => {
  await mongoose
    .connect(mongoURI, {
      useNewUrlParser: true
    })
    .then(() => called())
}

module.exports = mongoDB;

output:-

[nodemon] starting `node .index.js`
Example app listening on port 5000
Connection successful!
reaching here?????

In the tutorial the data comes up instantly. Is there something that I’m not doing?

2

Answers


  1. Try await until u find all the data

    async function called(){
      console.log('Connection successful!');
      const fetched_data = await mongoose.connection.db.collection("foodCategory");
      console.log('reaching here?????')
      await fetched_data.find({}).toArray(function(err, data){
        if(err) console.log(err);
        else console.log(data);})
    };
    Login or Signup to reply.
  2. You can modify the called() function like this:

    async function called() {
    console.log('Connection successful!');
    const FoodCategory = mongoose.model('FoodCategory', new mongoose.Schema({}));
    const data = await FoodCategory.find().exec();
    console.log(data);
    }
    

    May be it’s work!!

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search