【问题标题】:Mongodb nodejs driver not returning JSON dataMongodb nodejs驱动程序不返回JSON数据
【发布时间】:2020-01-21 03:04:11
【问题描述】:

我被困在我的 GET Route 端点上,将一个 JSON 数据数组从 MongoDB 返回到我的 localhost:5000 服务器,因此我可以为我的前端检索它 axios。到目前为止,我的代码只有控制台在 Visual Studio Code 中的服务器终端上使用前端所需的数据注销文档

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

  }); 

这是获取路由的前端 Reactjs 代码

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

【问题讨论】:

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

标签: node.js reactjs mongodb


【解决方案1】:

您的代码很好:问题出在您的数据库上。 在此工作codesandbox 的示例中,我将您的请求替换为 https://jsonplaceholder.typicode.com/users 效果很好。

【讨论】:

    【解决方案2】:

    问题是您关闭连接并在光标耗尽之前响应用户。

    游标耗尽后需要终止连接并响应请求Refer to the Docs

    这是您的代码的修改版本:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-04-23
      • 2014-06-29
      • 1970-01-01
      • 1970-01-01
      • 2013-09-06
      相关资源
      最近更新 更多