简体   繁体   English

如何从 MongoDB 获取数据?

[英]How to fetch data from MongoDB?

I am trying to use Express + MongoDB building React app.我正在尝试使用 Express + MongoDB 构建 React 应用程序。

I was able to post some documents to MongoDB.我能够将一些文件发布到 MongoDB。 Currently, I'm trying to figure out how to print fetched data to the screen.目前,我正在尝试弄清楚如何将获取的数据打印到屏幕上。

I have these routes:我有这些路线:

router.post('/totalbalance', (request, response) => {
    const totalBalance = new TotalBalanceModelTemplate({
        totalBalance:request.body.totalBalance,
    });
    totalBalance.save()
    .then(data => {
        response.json(data);
    })
    .catch(error => {
        response.json(error);
    });
});

router.get('/totalbalance', (request, response) => {
    TotalBalanceModelTemplate.find(request.body.totalBalance, (error, data) => {
        if (error) {
            return error
        } else {
            response.json(data[0])
        }
    })
});

This is axios request:这是 axios 请求:

   useEffect(() => {
        const resp = axios.get('http://localhost:4000/app/totalbalance');

        console.log(resp);
    }, []);

It returns a promise that has a parameter data which equals to object value which is the first value in the array它返回一个 promise ,其参数data等于 object 值,这是数组中的第一个值

data: {_
    id: "60c48b4ec60919553d92319f", 
    totalBalance: 5555, 
    __v: 0
}

and prints it out to the console.并将其打印到控制台。

How can I print out to the console the value totalBalance instead of whole promise?如何将值totalBalance而不是整个 promise 打印到控制台?

By the way, sometime the array of data is empty (there are no documents in the DB), how should i handle these cases as well?顺便说一句,有时data数组为空(数据库中没有文档),我应该如何处理这些情况?

Thanks!谢谢!

First of all, Axios GET method does not have any request body.首先,Axios GET 方法没有任何请求体。 But you are trying to use it in the MongoDB query.但是您正尝试在 MongoDB 查询中使用它。 - "TotalBalanceModelTemplate.find(request.body.totalBalance, (error, data) => {". -“TotalBalanceModelTemplate.find(request.body.totalBalance,(错误,数据)=> {”。

The find query should be object {}.查找查询应为 object {}。 If require pass on conditions to it.如果需要将条件传递给它。

First point, to print only "totalBalance" output.第一点,只打印“totalBalance”output。 Use, console.log(resp.totalBalance);使用,console.log(resp.totalBalance);

Second point, to handle records length, have a if else condition,第二点,处理记录长度,有一个if else条件,

    if (error) {
       return error
    } else if (data.length) {
       return response.send("No records found")
    } else {
       response.json(data[0])
    }

Try this:尝试这个:

Routes路线

router.post("/totalbalance", async (req, res) => {
  try {
    const totalBalance = new TotalBalanceModelTemplate({
        totalBalance: req.body.totalBalance,
    })
    await totalBalance.save();
    res.json(totalBalance)
  } catch (error) {
    res.status(400).json({
      message: error.message
    })
  }
})

router.get("/totalbalance", async (req, res) => {
  try {
    const totalBalances = await TotalBalanceModelTemplate.find();
    res.json(totalBalances)
  } catch (error) {
    res.status(400).json({
      message: error.message
    })
  }
})

App.js应用程序.js

import React, { useState, useEffect } from 'react';
import axios from 'axios';

export default function App() {
  const [data, setData] = useState([]);

  const getData = async () => {
    try {
      const response = await axios.get('http://localhost:4000/app/totalbalance');
      await setData(response);
    } catch (error) {
      console.log(error);
    }
  };

  useEffect(() => {
    getData();
  }, []);

  return (
    <div>
      {data <= 0 ? (
        <div className="empty">
          <p>No data!</p>
        </div>
      ) : (
        data.map((d) => (
          <ul key={d.id}>
            <li>{d.totalBalance}</li>
          </ul>
        ))
      )}
    </div>
  );
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM