-1

I am having trouble returning some database values to my server in nodejs, it seems that on the way the values are lost.

result is loged fine and i am findining my data, but it is lost in the return.

exports.getProducts = async function () {

return await MongoClient.connect(url, {useNewUrlParser: true}, async function 
(err, client) {
let db = client.db(dbName);
return await db.collection('products').find({}).toArray(async function (err, 
result) {
  if (err) throw err;
  client.close();
  console.log(result);
  return await result
});
});
}
JNF
  • 3,696
  • 3
  • 31
  • 64
Bowa
  • 13
  • 5
  • 2
    Please post your code and do not include a image of it. – Patrick Hollweck Sep 03 '18 at 18:59
  • [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – In general, what you're trying to do isn't really possible (like ordering food [`find`] and expecting to eat [`return result`] before it's actually been cooked [mongo being the kitchen]). Also, `return` statements work on the nearest `function`, which would be the callback that you aren't directly invoking, rather than `getProducts` (and, another Q&A, linked to in the 1st, dives into a common attempt at getting around that). – Jonathan Lonowski Sep 03 '18 at 19:46

2 Answers2

0

you should learn about asynchronous, callback and promise in javascript, after that you can work with javascript easily, and my code below can be understandable to you.

Lucky for us that now is 2018, the syntax of running synchronous function is super easy with async/await. In this case getProducts should be run synchronously and should be like this:

app.get('/api/products/', async function(req, res, next) {
    const myData = await mongo.getProducts();
    res.send(myData);
});

edit: mongodb.js should be update a little bit:

exports.getProducts = function() {
   return mongoClient.connect(url, {useNewUrlParser: true }, function(err, client) { 
      let db = client.db(dbName);

      return db.collection('products').find({}).toArray( function(err, result) { . 
          if(err) throw err;
          client.close();
          return result;
   }
   })
}

Q: what's the difference? A: awaitis waiting for a Promise be resolved with value. So that, getProducts have to return a Promise.

Kai
  • 3,104
  • 2
  • 19
  • 30
  • Okay so i need to make it asyncrounous. Your code is still not working. Ive noticed you return for every new nested function, it did not help. The result still wont pass all the way – Bowa Sep 03 '18 at 19:16
  • @Bowa those codes above is just describing my idea not the fix. I tried to point out what you're missing. and Yes, you have to return `Promise` to outside function :) – Kai Sep 04 '18 at 12:13
  • I've updated my code accordingly and read upon async functions. It stills gives me a undefined value. I think this has to do with the nature if mongodb as firebase works perfectly with the code above? – Bowa Sep 05 '18 at 07:50
0

Here try this code in mongodb.js

const MongoClient=require('mongodb').MongoClient
const assert=require('assert')


const url='mongodb://localhost:27017';

const dbName="productstoredb"


var Result;
var MongoDB;

var MongoConnect = new Promise((resolve, reject) => {
    var Db = MongoClient.connect(url, { useNewUrlParser: true }, function (err, client) {
        if (err) {
            resolve("error")
        }
        MongoDB = client.db("dbName")
        MongoDb.db(dbName)
        resolve("connected to the Database")
    })
})

var MongoView = new Promise((resolve, reject) => {
    MongoDB.collection("products").find().toArray(function (err, result) {
        if (err) resolve("ERROR");
        Result = result;
        resolve("success")
    })
})

exports.getProducts = async function () {
    console.log(await MongoConnect);
    console.log(await MongoView);
    return Result;
}

and also add await on your api

app.get('/api/products', function (req, res) {
    var mydata = await mongo.getProducts();
    res.send(Mydata)

})

you should google Promise,async-await.The connection to your mongodb doesnt happen instantaneously.Your code makes the call to connect to your database then It starts executing the next line of code even before that connection is established.

xxxgrime
  • 43
  • 8
  • Sorry that gives me the same result of undefined, I wonder if mongoDB does something differently. This works perfect with firebase for example. – Bowa Sep 04 '18 at 07:45
  • Does your `mongod.exe` instance register the connection?? – xxxgrime Sep 04 '18 at 15:50