0

I've been testing with this for hours not, but I can't figure out how to make the values I get not be undefined when I return them, as when I console.log it, it works fine but when I return the same object it says Promise { undefined }

Here's the code:-

    function db(fetch) {
    var MongoClient = require('mongodb').MongoClient;
    var url = require('./config.json').mongoURL;
    MongoClient.connect(url, function (err, db) {
        if (err) throw err;
        db.db("test").collection("jsons").findOne({
            ID: fetch
        }, function (err, result) {
            if (err) throw err;

            return result.data; // this is not returning data, even tho console.logging this works.
        });
    });
}
db('aiChannels')
  • What are you trying to return *to*? – Mitya Nov 03 '20 at 10:31
  • like I want to do like db(‘Something’) and I want its value which is inside the db as response, so I amtrying to return the “result” from the function – BeIntelligent Nov 03 '20 at 10:46
  • Aha in that case see the duplicate - you're trying to return a value from an asynchronous operation which, because returns are synchronous, doesn't work. You'll need a promise or callback structure of some sort. – Mitya Nov 03 '20 at 14:12
  • Any links to callback/promise structure? As its my first time playing with functions. – BeIntelligent Nov 03 '20 at 16:16
  • Look at the answers on the linked duplicate question and read up about promises. I myself wrote an [in-depth guide to them](https://mitya.uk/articles/javascript-promises-part-1). – Mitya Nov 04 '20 at 10:28

0 Answers0