MongoDb query return empty object

Issue

I’m trying to perform a simple .find() query on my mongodbAtlas, but the result of this query is an empty object.

this is my server file:

require("dotenv").config({ path: "./config.env" });
const { MongoClient, ServerApiVersion } = require("mongodb");
const express = require("express");
const { ServiceBroker } = require("moleculer");
const AUTH_SERVICE = require("./controller/services/auth/auth.service");

global.broker = new ServiceBroker({
  nodeID: "auth",
});

const app = express();
app.use(express.json());
app.use("/auth", require("./routes/auth"));

const { PORT, URI } = process.env || 5000;

global.broker.createService(AUTH_SERVICE);

const start = async () => {
  const dba = await MongoClient.connect(URI, {
    useNewUrlParser: true,
    useUnifiedTopology: true,
  });
  global.db = dba.db("Auth");

  try {
    await dba.connect();
    console.log("DATABASE CONNESSO CON SUCCESSO📡");
  } catch (e) {
    console.error(e);
  }

  await global.broker.start();
  app.listen(PORT, () => console.log(`PORT IT'S UP AND RUNNING 🚀 ON ${PORT}`));
};
start();

this is my routes file:

const express = require("express");
const router = express.Router();

router.get("/register", async (req, res) => {
  const data = global.db.collection("Users").find({}).toArray();
  res.send(data);
});


module.exports = router;

this is how my document is populated:

{"_id":{"$oid":"6297bbc83a95b81d74882f65"},"username":"Test","email":"test@gmail.com","password":"1234"}

Solution

I think you are missing the "await" keyword after const data….. as API data fetching calls are asynchronous and required promise/ async-await to handle. Being async in nature, it moves forward to the next instruction and returns an empty array.

const express = require("express");
const router = express.Router();

router.get("/register", async (req, res) => {
const data = await global.db.collection("Users").find({}).toArray();
  res.send(data);
});

module.exports = router;

Answered By – Rishabh Kumar Mayank

Answer Checked By – Candace Johnson (AngularFixing Volunteer)

Leave a Reply

Your email address will not be published.