db.collection().find() not returning any data

Hello, I have created some JSON documents and populated them with data. One of these documents is named Biens.json. When I execute db.Biens.find() on the MongoDB shell, it successfully retrieves and displays the data. However, when I attempt to retrieve the same data using a RESTful approach, nothing is displayed; only an empty array [] is returned. I am using a Mac, and I have already installed and imported Express and MongoDB. To run the code, I use the command node serveur.js .

Here is my code : `var express = require(“express”);
var app = express();

async function main() {
var MongoClient = require(“mongodb”).MongoClient;
var url = “mongodb://localhost:27017”;
const client = new MongoClient(url);
const connexion = await client.connect();
console.log(‘Connecté à la base de données’);
db = connexion.db(“MEAN”);

app.get("/Biens", async (req, res) => {
    let nbDocuments = await db.collection("Biens").countDocuments();
    let documents = await db.collection("Biens").find().toArray();



your code looks to me a little spagetthi code with that “async main”. try first clearing your code. It may solve itself when you do so.

  • you are using “async” main function. you need to wait for it to complete its run. otherwise, the program will not behave as you would expect. try “await main()
  • your client is not global (let and const, not var), so this may cause connection problems for that endpoint. try setting your client as a singleton outside.
  • move the definition for that endpoint outside along with above step.
  • you start server too early before you before you set up all endpoints. this may cause problems, especially when using async functions. move server start up line to the end of file.

also there maybe more than one async approach used in the chain, but “await” may not wait at each node. also try to split “find” and “toArray” into 2 lines.

check these steps, then tell use more if they won’t solve your problem.

1 Like

adding to my previous post…

Sometimes, the answer might be obvious but we may fail to see it. That happens all the time. Unfortunate I don’t have a proper setup to test your code. Try my suggestions so you may see it yourself (and learn things you miss on the way), or maybe you are lucky and someone else with a sharp eye comes in.

Cheers :wink:

1 Like