如何从MongoDB中获取数据? [英] How to fetch data from MongoDB?

查看:135
本文介绍了如何从MongoDB中获取数据?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 Express + MongoDB 构建 React 应用程序.

I am trying to use Express + MongoDB building React app.

我能够将一些文档发布到 MongoDB.目前,我正在尝试弄清楚如何将获取的数据打印到屏幕上.

I was able to post some documents to MongoDB. Currently, I'm trying to figure out how to print fetched data to the screen.

我有这些路线:

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

这是 axios 请求:

This is axios request:

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

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

它返回一个promise,它有一个参数data,它等于对象值,它是数组中的第一个值

It returns a promise that has a parameter data which equals to object value which is the first value in the array

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

并将其打印到控制台.

如何将值 totalBalance 而不是整个 promise 打印到控制台?

How can I print out to the console the value totalBalance instead of whole promise?

顺便说一句,有时data的数组是空的(数据库中没有文档),我该如何处理这些情况?

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?

谢谢!

推荐答案

首先,Axios GET 方法没有任何请求体.但是您正在尝试在 MongoDB 查询中使用它.- "TotalBalanceModelTemplate.find(request.body.totalBalance, (error, data) => {".

First of all, Axios GET method does not have any request body. But you are trying to use it in the MongoDB query. - "TotalBalanceModelTemplate.find(request.body.totalBalance, (error, data) => {".

查找查询应该是对象 {}.如果需要将条件传递给它.

The find query should be object {}. If require pass on conditions to it.

第一点,只打印totalBalance";输出.使用,console.log(resp.totalBalance);

First point, to print only "totalBalance" output. Use, console.log(resp.totalBalance);

第二点,处理记录长度,有个if else条件,

Second point, to handle records length, have a if else condition,

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

这篇关于如何从MongoDB中获取数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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