简体   繁体   中英

Fetch all data from mongodb

I'm trying to fetch all the data i have in my mongodb collection and for some reason i can't do it.

I can get more than one result but if i try to get more than x results, it stops working.

I'm using Flask, MongoDB, pymongo to work with mongodb and React.

This is my Flask function.

@ app.route("/escoller-centro-proba", methods=["POST"])
@ cross_origin()
def search_proba():
    if request.method == "POST":
        centros = []
        resultadosPing = []
        resultadosNmap = []
        codigo = request.json['codigo'].upper()
        query = {"centro": {"$regex": codigo}}
        resultados = collection.find(query)

        for resultado in resultados:
            centroId = str(resultado["_id"])
            centros.append({"_id": centroId, "sf": resultado["sf"], "centro": resultado["centro"], "concello": resultado["concello"], "lan": resultado["lan"], "dhcp": resultado["dhcp"],
                            "tecnoloxia": resultado["tecnoloxia"], "tecnoloxia_respaldo": resultado["tecnoloxia_respaldo"], "eva": resultado["eva"]})

        if len(centros) > 1:
            return jsonify({"centros": centros, "resultadosPing": resultadosPing, "resultadosNmap": resultadosNmap})

        return jsonify({"centro": centros[0], "resultadosPing": resultadosPing, "resultadosNmap": resultadosNmap})
    else:
        return "Método non POST"

And here the JS function.

const escollerCentro = async (e) => {
        e.preventDefault()
        const res = await instance.post("http://127.0.0.1:5000/escoller-centro-proba", {
            codigo: codigo.trim().toUpperCase()
        })

        console.log(res.data)

        if (res.data.centro === "O centro non existe") {
            setError("O centro non existe")
            setIsError(true)
            return;
        }

        if (res.data.centros) {
            tabsInfoVar[value].cras = res.data.centros
            tabsInfoVar[value].centro = {
                centro: "",
                resultadosPing: [],
                resultadosNmap: []
            }
        } 
        if (res.data.centro) {
            tabsInfoVar[value].centro = {
                img: img,
                centro: res.data.centro.centro,
                index: res.data.centro._id,
                concello: res.data.centro.concello,
                lan: res.data.centro.lan,
                dhcp: res.data.centro.dhcp ? "Si" : "Non",
                sf: res.data.centro.sf,
                tecnoloxia: res.data.centro.tecnoloxia,
                tecnoloxia_respaldo: res.data.centro.tecnoloxia_respaldo,
                eva: res.data.centro.eva,
                resultadosPing: [],
                resultadosNmap: []
            }
            tabsInfoVar[value].cras = []
        }
        
        tabsInfoVar[value].resultadosPing = res.data.resultadosPing
        tabsInfoVar[value].resultadosNmap = res.data.resultadosNmap

        const resultadosPing = []
        for (var i = 0; i < tabsInfoVar[value].resultadosPing.length; i++) {
            if(tabsInfoVar[value].resultadosPing[i] !== null) {
                resultadosPing.push(tabsInfoVar[value].resultadosPing[i])
            } else {
                console.log("Resultado con valor nulo")
            }
        }
        
        const resultadosNmap = []
        for (var i = 0; i < tabsInfoVar[value]?.resultadosNmap.length; i++) {
            if(tabsInfoVar[value].resultadosNmap[i] !== null) {
                resultadosNmap.push(tabsInfoVar[value].resultadosNmap[i])
            } else {
                console.log("Resultado con valor nulo")
            }
        }

        tabsInfoVar[value].resultadosPing = resultadosPing;
        tabsInfoVar[value].resultadosNmap = resultadosNmap;
        setTabsInfo([...tabsInfoVar])
    }

As I said, if i fetch less than 13 results, the code works. I get an array from the database and my frontend can work with it. Here an example: I searched "RIANXO" and it shows me all the results that contains "Rianxo".

在此处输入图像描述

Here I'm searching "CRA", it should show an array of 168 results. Instead, i get this:

在此处输入图像描述

It shows all the results but not an array and as you can see, there is a label ("Show more") that I have to press if I want to see all the data.

I think it is a problem with mongodb, because i did exactly this but working with excel instead of mongodb and had no problem fetching all the data, 1275 results.

Thank you all.

I have found the problem. When i saved all the data from excel to mongodb, empty cells filled with NaN value and when the frontend was trying to get the attribute it was displaying the data in the way i have already shown.

The answer was to modify the value of those cells with df = df.fillna (" ") .

Here is the code:

for index, centro in enumerate(centros):
   data = df[df["Centro"].str.contains(centro)]
   id = df.iloc[index]["ID"]
   centro = df.iloc[index]["Centro"]
   concello = df.iloc[index]["Concello"]
   lan = df.iloc[index]["LAN"]
   dhcp = df.iloc[index]["DHCP"]
   tecnoloxia = df.iloc[index]["Tecnoloxía Acceso Principal"]
   tecnoloxia_respaldo = df.iloc[index]["Tecnoloxía Acceso Respaldo"]
   eva = "Non"
   if dhcp == "Si":
       dhcp = True
   else:
       dhcp = False
   lan = format_lan(lan)
   df = df.fillna("")
   if tecnoloxia_respaldo == "":
       tecnoloxia_respaldo = "Non ten liña de backup"
   centroNovo = {"sf": id, "centro": centro, "concello": concello, "lan": lan, "dhcp": dhcp,
                 "tecnoloxia": tecnoloxia, "tecnoloxia_respaldo": tecnoloxia_respaldo, "eva": eva}
   print(centroNovo)
   collection.insert_one(centroNovo)

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