MongoDB查找不返回数组 [英] Mongodb find doesn't return array

查看:95
本文介绍了MongoDB查找不返回数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不确定我在这里缺少什么.我想在Nodejs函数中查询MongoDB数据库.下面的jobs变量始终返回未定义状态.我期望它返回一个数组.如果我在collection.find中运行console.log,它将输出我要返回的数组.

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

推荐答案

client.connectasync函数,并接受回调.您不能在回调作用域之外访问jobs变量.

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

为此,您可以将client.connect方法包装到一个函数中,并可以从那里返回promise.

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

这篇关于MongoDB查找不返回数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆