3

I'm not sure what I'm missing here. I would like to query a MongoDB Database within a Nodejs function. The jobs variable below, keeps returning undefined. I'm expecting it to return an array. If I run a console.log within collection.find it outputs the array I'm trying to return.

async function getDataFromMongoDB(page) {
  const MongoClient = require("mongodb").MongoClient;
  const uri = "mongodb://localhost:3001";
  const client = new MongoClient(uri, { useNewUrlParser: true });
  client.connect(async function(err) {
    console.log(5, err);
    const collection = client.db("meteor").collection("jobs");

    const jobs = await collection.find().toArray((err, items) => {
      return items;
    });
    console.log("jobs", jobs);

    // return jobs;
    // console.log(jobs);

    // perform actions on the collection object
    client.close();
  });
}
2
  • Try for const jobs = await collection.find().toArray(); console.log(jobs) Commented Nov 5, 2019 at 4:11
  • Thanks, @Subburaj that works but I still can't get jobs out of client.connect. Commented Nov 5, 2019 at 4:17

1 Answer 1

3

client.connect is async function and accepts callback. You cannot access the jobs variable outside the callback scope.

To do so you can wrap the client.connect method into a function and can return promise from there.

async function getDataFromMongoDB(page) {
  const MongoClient = require("mongodb").MongoClient;
  const uri = "mongodb://localhost:3001";
  const client2 = new MongoClient(uri, { useNewUrlParser: true });
  const client = await connectToMongodb(client2)
  const collection = client.db("meteor").collection("jobs");
  const jobs = await collection.find().toArray();
  console.log("jobs", jobs);
}

connectToMongodb(client) {
  return new Promise((resolve, reject) => {
    client.connect(function(err) {
      return resolve(client)
    });
  })
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.