0

I would like to fetch all the data (users) from a localdb using mongodb and node.js. but res.json(usersArray) is not displaying anything. I also tried to use .render but it would give me another error.

var express = require('express');
var mongojs = require('mongojs');
var db = mongojs('mongodb://localhost/mydb', ['users']);
var app = express();
const port = 5000;

app.use(express.static(__dirname + "/public"));
app.get('/', function(req, res){
    console.log("I received a GET request")


    /*
    db.users.find(function(err, docs){
        console.log("Getting data from db");
        console.log(docs);
        //res.json(docs);
    });
    */

    let usersArray = db.users.find().toArray(function(err, docs){
        console.log("Getting data from db");
        console.log(docs);
        //res.json(docs);
    });;

    res.json(usersArray);

    //usersString = JSON.stringify(usersArray);

    //res.render(usersString);

    //res.json(usersString);

    console.log("Returned data");

});

app.listen(port,'0.0.0.0');
console.log('Server running on port '+port);
demonslayer1
  • 741
  • 2
  • 16
  • 24
  • Why did you comment out `res.json(docs)`? The MongoDB find is *asynchronous*, `usersArray` is probably `undefined` (or maybe a promise). – jonrsharpe Aug 28 '19 at 10:28
  • 2
    Possible duplicate of [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) – jonrsharpe Aug 28 '19 at 10:29
  • because res.json(docs) would just return an empty array and also I can use res.json only once in the program. – demonslayer1 Aug 28 '19 at 10:33
  • 1. Then there aren't any users to find; and 2. only once *in that handler*, and that's true for any request; why would you want to use it more than once? – jonrsharpe Aug 28 '19 at 10:34

1 Answers1

1

use async await to block promise-based asynchronous functions

app.get('/', async function(req, res){
    console.log("I received a GET request")


    let usersArray = await new Promise((resolve, reject) => {
      db.users.find().toArray((err, docs) => {
        if (err)
         reject(err)
        resolve(docs)
      })

   });

   res.json(usersArray);

    //usersString = JSON.stringify(usersArray);

    //res.render(usersString);

    //res.json(usersString);

    console.log("Returned data");

});
Jasper Bernales
  • 1,601
  • 1
  • 11
  • 16