Mongodb find doesn't return array

前端 未结 1 1511
长发绾君心
长发绾君心 2021-01-20 18:28

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\'

1条回答
  •  后悔当初
    2021-01-20 19:29

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

    0 讨论(0)
提交回复
热议问题