0

I am using MEAN stack for crud operation where I am testing my backend routes for that I am using postman. When I am trying to get the data from database I am getting an empty array in response and in nodejs console. help me for the same

router.get('/getUser',async(req,res)=>{
try {
   await client.connect(url,{ useUnifiedTopology: true },async(err,db)=>{
        if(err) throw err;
        let dbo = db.db("company");
        console.log("connected to database");
        let fetchedUsers = await dbo.collection("employee").find({}).toArray((err,result)=>{
            if(err) throw err;
            console.log(result);
            res.json(result);
            db.close();
        });
        // await fetchedUsers.forEach((user)=>{
        //     console.log(user);
        // });
        // await res.json(fetchedUsers);
        // await db.close();
    
    });
} catch (error) {
    
    res.send("Something happened" + "  "+error);
}
Akshay
  • 19
  • 4
  • Does this answer your question? [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) – Matt Morgan Mar 16 '21 at 11:26
  • thank you for your help @MattMorgan but it is not helpful as of now. – Akshay Mar 16 '21 at 11:29
  • So this line `console.log(result);` prints empty array `[]` to console, right? If so then there are no data in your db. I would recommend you to create for example testdb.js file and test db stuff separately from the other code just printing the results to terminal. Once the code runs as it should place it back to routes and test it with Postman – Molda Mar 16 '21 at 11:53
  • @Molda I have data present in my database. I have performed post operation successfully any suggestions? – Akshay Mar 16 '21 at 12:01
  • 1
    Well if there's no error and it returns an empty array then there are no data. So maybe you have some typo in dbname or collection. Also you are using async/await and callbacks which is not right. You should use one or the other. Either use this `let fetchedUsers = await dbo.collection("employee").find({})` without the `toArray`(async/await) or use `dbo.collection("employee").find({}).toArray((err...` without `let fetchedUsers = await` (callback) – Molda Mar 16 '21 at 12:08
  • 1
    i don't think you should be mixing 'await' with the async callback - really not sure what's gonna happen then. afaik it's a one-or-the-other approach – batman567 Mar 25 '21 at 09:44

0 Answers0