0

In the controller, it searches the countries collection for all countries. Inside db.db.collection .... I have console.log (countries). It works because the terminal returns me all countries. But res.json (countries) doesn't work. On the client side, it returns to me data: ''. How can I put the content returned by return countries in res.json()?

//controllers/countries

module.exports.read = (req, res) => {     
    const countries = db.db.collection('countries').findOne({}, function (findErr, countries) {
        if (findErr) throw findErr;
        console.log(countries); //it works, in terminal return me all countries

        return countries;
        });

    res.json(countries);
};
Umbro
  • 1,984
  • 12
  • 40
  • 99
  • Just move the `res.json` next to the `console.log` call where `countries` is available. And don't do `throw findErr` in a callback - instead, send an error response! – Bergi Oct 11 '20 at 16:32

1 Answers1

1

This is a typical case of calling a return before an async function has finished. Many people get this wrong. You need to call the "returning" callback in the callback from the db find:

module.exports.read = (req, res) => {     
  db.db.collection('countries').findOne({}, function (findErr, countries) {
    if (findErr) throw findErr;
    console.log(countries); //it works, in terminal return me all countries
    res.json(countries);
  });
};
Christian Fritz
  • 20,641
  • 3
  • 42
  • 71