简体   繁体   中英

How to fetch data from MongoDB?

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

I was able to post some documents to 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:

   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

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?

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?

Thanks!

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.

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

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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