简体   繁体   中英

Asynchronous request from database in node.js

i am making an asynchronous request to a database and then running a loop on the resultant data but i am getting only the last value while sending a response to front-end

routes.post('/data/qualitative/bivariate', async (req, res)=>{
    const { colName1, colName2} = req.body;
    var colNameObj1={};
    var colNameArray1={};
    colNameObj1[colName1]=1;
    colNameObj1[colName2]=1;
    colNameObj1['_id']=0;

    //requesting data from database
    const data= await dataModel.find({}, colNameObj1);

    //filtering the data
    const newData= data.map( (item)=>{
        colNameArray1['x']=  item[colName1];
        colNameArray1['y']=  item[colName2];
        return colNameArray1
    })

    //in response i am getting just the data from the last index
    res.json(newData)
})

In response i am getting just the data from the last index. Please advise how i can handle this asynchronous request

If you want all the rows, then you should push each object you can create in to an array. In the above code, you are overwriting over the same object.

Try updating the code to the following:

routes.post('/data/qualitative/bivariate', async (req, res)=>{
    const { colName1, colName2} = req.body;
    var colNameObj1={};
    var colNameArray1={};
    const dataList = [] // Create a empty array
    colNameObj1[colName1]=1;
    colNameObj1[colName2]=1;
    colNameObj1['_id']=0;

    //requesting data from database
    const data= await dataModel.find({}, colNameObj1);

    //filtering the data
    data.forEach( (item)=>{
        colNameArray1['x']=  item[colName1];
        colNameArray1['y']=  item[colName2];
        dataList.push(colNameArray1) // Push to the array
    })

    //in response i am getting just the data from the last index
    res.json(dataList)
})

You must declare colNameArray1 inside the map function:

routes.post('/data/qualitative/bivariate', async (req, res)=>{
    const { colName1, colName2} = req.body;
    var colNameObj1={};
    colNameObj1[colName1]=1;
    colNameObj1[colName2]=1;
    colNameObj1['_id']=0;

    //requesting data from database
    const data= await dataModel.find({}, colNameObj1);

    //filtering the data
    const newData= data.map( (item)=>{
        var colNameArray1={};
        colNameArray1['x']=  item[colName1];
        colNameArray1['y']=  item[colName2];
        return colNameArray1
    })

    //in response i am getting just the data from the last index
    res.json(newData)
})

i found the issue and it has nothing to do with the asynchronous request and as mentioned above its confirmed that i am overwriting the object. Cloning the object using spread {... obj} has solved the issue. Thanks for help.

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