Mongodb find doesn't return array

2020-04-10 02:29发布

问题:

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();
  });
}

回答1:

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)
    });
  })
}