Home > front end >  Map function not working for properly while querying from Mongodb
Map function not working for properly while querying from Mongodb

Time:02-22

I have a few mongodb documents like this

{'_id':'1',
 'year':2020,
 'season':'Summer',
 'status':'Over'},

{'_id':'2',
 'year':2020,
 'season':'Winter',
 'status':'Pending'},

{'_id':'3',
 'year':2020,
 'season':'Rainy',
 'status':'Pending'},

{'_id':'4',
 'year':2021,
 'season':'Summer',
 'status':'Pending'}
........
...
.

If I give an input of array of years [2020,2021], then my expected output should be

[{year:2020,sesason:['Winter','Rainy']},{year:2021,sesason:['Summer','Winter','Rainy']}]

where season array should only contain values whose status is 'Pending'. I tried this code,but not getting the expected output

var arr =[];
var yearsArray = [2020,2021]
var seasonArray = ['Summer','Rainy','Winter']
var pendingSeasons = [];
return await Promise.all(
   yearsArray.map(async(year) =>{
      return await Promise.all(
         seasonArray.map(async(tP) =>{
             await db.collection('CC')
              .find({'year':year,'season':tP})
              .toArray()
              .then((data) =>{
                    if(data.status != 'Over'){
                        pendingSeasons.push(tP)
                    }
                })
            })
        ).then(arr.push({"year":year,"season":pendingSeasons}))
        })
        ).then(() =>{
            return arr
        })

The output I am getting is given as below :

[
{
    "year": 2020,
    "season": [
        "Summer","Rainy","Winter","Summer","Rainy","Rainy","Summer",
        "Winter","Winter"]
},
{
    "year": 2021,
    "season": ["Summer","Rainy","Winter","Summer","Rainy","Rainy",
        "Summer","Winter","Winter"]
}
]

CodePudding user response:

The problem is where you are comparing two strings.

if(data.status != 'Over'){
    pendingSeasons.push(tP)
}

It should be like:

if(data.status.localeCompare("Over") != 0){
    pendingSeasons.push(tP)
}

CodePudding user response:

Got the answer

var Data = db.collection('CC').find({}).toArray();
var yrsArray = [2020,2021]
var seasonArray = ['Summer','Rainy','Winter']
let yrResult = [];
let yrObj = {}
yrsArray.forEach((element) => {
   yrObj = {};
   yrObj.year = element;
   let season = [];
   let year = Data.filter((element1) => element1.year == element)
   for (var i=0;i<seasonArray.length;i  ){
       const currentSeason = year.filter((element)=>element.season == 
                                   seasonArray[i])
       if(currentSeason.length == 0){season.push(seasonArray[i])}
                else if(currentSeason[0].status != "Over") 
                          {season.push(seasonArray[i])}
                yrObj.season = season;
   }
   yrResult.push(yrObj)
})
return yrResult
  • Related