Node.js Mongodb nodejs驱动程序不返回JSON数据

Node.js Mongodb nodejs驱动程序不返回JSON数据,node.js,reactjs,mongodb,Node.js,Reactjs,Mongodb,我被困在GET-Route端点上,无法将数据的JSON数组从MongoDB返回到localhost:5000服务器,这样我就可以为我的前端检索axios。到目前为止,我的代码专用控制台在VisualStudio代码中注销服务器终端上的文档,其中包含前端所需的数据 这是GET路由的服务器代码 app.get('/pets', function(req, res){ const resultArray = []; client.connect(err => { assert.equal

我被困在GET-Route端点上,无法将数据的JSON数组从MongoDB返回到localhost:5000服务器,这样我就可以为我的前端检索axios。到目前为止,我的代码专用控制台在VisualStudio代码中注销服务器终端上的文档,其中包含前端所需的数据

这是GET路由的服务器代码

app.get('/pets', function(req, res){
const resultArray = [];
client.connect(err => {
    assert.equal(null, err);
    console.log("Connected successfully to server");
    const db = client.db(dbName);
    const cursor = db.collection('pet').find({});
iterateFunc = (doc,err) => {
        assert.equal(null, err);
        resultArray.push(doc);
        console.log(JSON.stringify(doc, null, 4));
        if(err) {
            console.log(err)
    }
    }
        cursor.forEach(iterateFunc);
        client.close();
        res.send({pets: resultArray});

  }); 
下面是get路由的前端代码

import React, {
  Component
}
from 'react';
import axios from 'axios';

export default class ListPets extends Component {

  constructor(props) {
    super(props);
    this.state = {
      pets: [],
      isLoaded: false,
    }
  }

  componentDidMount = () => {
    this.getPets();
  };

  getPets = async() => {
    const res = await axios.get('http://localhost:5000/pets/');
    const pets = res.data;
    this.setState({
      isLoaded: true,
      pets: pets
    });
    console.log('Data has been received!');
    console.log(pets.data)
    return pets;
  }

  render() {
    console.log('State: ', this.state);
    const {
      isLoaded,
    } = this.state;

    if (!isLoaded) {
      return <div> Loading... </div>;
    } else {
      return (<div></div>);
    }
  }
}
import-React{
组成部分
}
从"反应",;
从“axios”导入axios;
导出默认类ListPets扩展组件{
建造师(道具){
超级(道具);
此.state={
宠物:[],
isLoaded:false,
}
}
componentDidMount=()=>{
这个。getPets();
};
getPets=async()=>{
const res=等待axios.get('http://localhost:5000/pets/');
常数=分辨率数据;
这是我的国家({
isLoaded:是的,
宠物:宠物
});
log('已收到数据!');
console.log(pets.data)
归还宠物;
}
render(){
console.log('State:',this.State);
常数{
孤岛,
}=本州;
如果(!已加载){
返回装载;
}否则{
返回();
}
}
}

您的代码很好:问题在于您的数据库。 在本工作的示例中,我将您的请求替换为
它工作得很好。

问题是,在光标用尽之前,您必须关闭连接并响应用户

您需要在游标用完后终止连接并响应请求

以下是您的代码的修改版本:

app.get('/pets', async function(req, res){
  try {
    let resultArray = [];


    const db = client.db(dbName);
    // this will return a promise and wait until it is fulfilled.
    resultArray = await db.collection('test-coll').find({}).toArray();

    client.close();
    console.log(' >>>> ',resultArray);
    res.send({pets: resultArray});
  }
  catch (error) {
    console.log('ERROR', error);
    client.close();
    res.status(400).send('ERROR');

  }
}
另外,您应该(我不知道您的情况)在服务器运行时保持数据库连接处于活动状态,因此您应该移动数据库连接并从路由处理程序关闭它

注意

toArray()
将获取整个数据集。您仍然可以像这样使用
cursor.forEach()

app.get('/pets', async function(req, res){
  try {
    const resultArray = [];
    const db = client.db(dbName);
    const cursor = db.collection('test-coll').find({});

    const endCallBack = (e) => { // called when all docs are read
      client.close();
      console.log(' >>>> ',resultArray);
      res.send(resultArray)
    }
    const iterateFunc = (doc,err) => {
      if(err) {
        return console.log(err)
      }
      if (doc) {
        resultArray.push(doc);
      }
    }
    cursor.forEach(iterateFunc, endCallBack);
  }
  catch (error) {
    console.log('ERROR', error);
    client.close();
    res.status(400).send('ERROR');
  }
}

前端的数据是什么样子的,我认为,由于数据正确地记录在服务器上(在字符串化之后),请尝试在find()之后调用
toArray()
find(),如下所示:db.collection('pet').find({})。toArray()这是浏览器控制台中的一个空数组pets:[]嗨,你对我的答案满意吗?你检查过提供的沙箱了吗?让我知道有什么问题,以便进一步帮助您