-1

What is wrong with this result? my res.send(dbResult) is not giving me any data. It is empty.

/* GET users listing. */
router.get('/', function(req, res, next) {

  async function getData(){
    try{
     var dbResult = await mongodb.findData("contacts","iyaiContacts");
     console.log('before dbResult');
     res.send (dbResult);
    }catch(error){
      console.log("error getting contacts...", error.message);
    }
  }
  getData();
});

Additional code for clarity. I have a db.js file that is used to handle the MongoDB connections and queries. Here is the Find Data function. Sorry I didn't realize I was being confusing until people asked questions.

const findData = (myColl, myDb) => {
  try {
    MongoClient.connect(
      url,
      function(err, client) {
        client
          .db(myDb)
          .collection(myColl)
          .find()
          .sort({ nmFull: 1 })
          .toArray(function(err, result) {
            console.log("find() result...", result);
            return result;
          });
      }
    );
  } catch (e) {
    console.log(`findData() error message is...${e.message}`);
    client.close(); // trying to close open db connection if it exist
    throw e;
  }
};
Trewaters
  • 949
  • 3
  • 13
  • 23

1 Answers1

1

You are writing a backend service for your app that need to fetch data from your MongoDB. The problem is that your handling functions in synchronous manor — instead you need to handle as asynchronous.

// Quick fix for your code

const findData = (myColl, myDb) => {
    return new Promise(function (resolve, reject) {
        MongoClient.connect(url)
            .then((client) => {
                return client.db(myDb)
            }).then((db) => {
                return db.collection(myColl).find().sort({ nmFull: 1 })
                    .toArray((err, result) => { resolve(result); });
            }).catch((err) => {
                reject(err);
            });
    });
};

Here are some best practice to connect MongoDB on Node.js,

Şivā SankĂr
  • 1,966
  • 1
  • 18
  • 34
  • Thanks for your help. That worked in my code. I didn't realize the db call was causing the issue. I thought it was in the API. – Trewaters Jan 20 '19 at 14:32