8SINS
8SINS

Reputation: 461

How to sum data fetched from mongoDB using Nodejs

I have created an application that stores attendance of employee in an organization. Each employee belonging to a different department. The challenge is, am trying to figure out how I can query MongoDB using mongoose such that I can obtain 7days worth of data of the total number that were present in a particular department.

I tried using the following, but am unable to figure out the query that will yield my desired result :

    const d =new Date(); 
    d.setDate(d.getDate()-7); ....//7days record 
    db.user.aggregate(["required query here"])... //record based on query

I haven't really got much experience in mongoose and Nodejs, just the basics.

Here is the stored info in my MongoDB database/collection


        {      //extracted from my mongoDB database

                "_id": "5d40c2a35a6da12cd8506fac",
                "name": "Jonhny Fredicks",
                "department": "Marketing", //department is first criteria
                "origin": "N/Y",
                "joinDate": "2019-07-30",
                "__v": 0,
                "attendances": {  
 // attendance is second criteria        
                    "2019-07-30": "Present",// total number of "present" is the final goal.This would be done for all employee with the same "department" field.
                    "2019-07-31": "Sick",
                    "2019-08-01": "Present",
                    "2019-08-02": "Present",
                    "2019-08-06": "Present",
                    "2019-08-08": "Vacation",
                    "2019-08-10": "Present",
                    "2019-08-12": "Sick",
                    "2019-08-21": "Present"
                }


I would really appreciate your suggestions: my goal is to be able to fetch those employees records, who were present in last 7 days, send it to the front-end where I will use that number to multiply their inputted hourly rate. hence compute their wages for the week.

Upvotes: 1

Views: 286

Answers (1)

user9744623
user9744623

Reputation:

Follow that hope you will able to find out the employee who are working for last 7 days out of 9 days.

router.get("/api",(req,res,next)=>{
      db.find().then((result)=>{
      var js=[];
      for(var a = 0;a<result.length;a++){
        obj=result[a];
        var counter =0;
        var name= Object.getOwnPropertyNames(obj.attendances);
        for(var i=0;i<name.length;i++){
          if(obj.attendances[name[i]]=="Present"){
            counter +=1;
          }
        }
        if(counter>=7){
          js.push(obj);
          console.log("Okay")
        }else{
          console.log("It's not okay")
        }
       }
       console.log(js);
        res.json({data:js});
       });
     });

Upvotes: 0

Related Questions