4

I'm having a difficulty showing my records from MongoDB. Basically I have some fields 'leaves_start' and 'leaves_end' in my MongoDB. This fields has the date range of the user's leave. See example below.

user_name : junel

leaves_start: 10/05/2015

leaves_end: 10/10/2015

I want to get all the records in my MongoDB if the current date (e.g 10/07/2015) is within the range of the record's leaves_start and leaves_end.

I already tried $gte and $lte but I'm a little bit confused on how to implement it on my current state.

Here's my sample method:

getTowerLeaveData_LV: function(dateToday,tower) {
    var arr = LeavesCollection.find($or: [ 
        { leaves_start: { $lte: dateToday } }, 
        { leaves_end: { $gte: dateToday } } ], 
        leaves_approval_status: {$ne: 'Rejected'}}).fetch();

        return arr
},

Here's my sample Mongodb Record

_____________________________________
name   |  leaves_start   | leaves_end
_____________________________________
Junel  | 10/01/2015      | 10/03/2015
_____________________________________
Jaycee | 10/03/2015      | 10/03/2015
_____________________________________
Tori   | 10/05/2015      | 10/10/2015
_____________________________________
Ryan   | 10/02/2015      | 10/05/2015

If the value of dateToday is 10/03/2015, then method should return the records of Junel, Jaycee and Ryan.

I hope that this makes sense. Thanks guys!

Junel
  • 69
  • 3
  • Can you click the [**edit**](http://stackoverflow.com/posts/33350365/edit) link to include the schema details, some sample data with the expected output? – chridam Oct 26 '15 at 16:10
  • Hi chidram, done updating. THanks! – Junel Oct 26 '15 at 16:24
  • Thanks for updating, can you clarify whether the `leaves_start` and `leaves_end` fields hold strings or Date objects? – chridam Oct 26 '15 at 16:26
  • The fields are holding strings. – Junel Oct 26 '15 at 16:26
  • In that case I would recommend storing your dates as Date or ISODate on MongoDB since it's much easier when using comparison operators like `"$gte"` /`"$lte"` on Date objects or integers (timestamps). You can convert your strings to date objects by referring to this other SO question: [**How do I convert a property in MongoDB from text to date type?**](http://stackoverflow.com/questions/2900674/how-do-i-convert-a-property-in-mongodb-from-text-to-date-type). – chridam Oct 26 '15 at 16:31
  • 1
    Hi chridam, thanks for the recommendations. I have successfully found a solution for my problem, though I didn't use $gte and $lte. – Junel Oct 27 '15 at 16:15
  • Awesome, would be really helpful to future readers if you can share your solution by answering your own question and even accepting it as the solution :) – chridam Oct 27 '15 at 16:20

3 Answers3

2
startDate =  ;// get Start Date from UI Convert it to date format using new Date();
endDate   =  ;// get End Date from UI Convert it to date format using new Date();
MyCollection.find({
  leaves_start: { $lte: endDate},   // start Less and endDate
  leaves_end:   { $gte: startDate } // end greater than StartDate
});

if the startDate and endDate is same you get all the records for that date , else it will be date Range.

gatolgaj
  • 1,193
  • 7
  • 12
1

You'd do it like this

MyCollection.find({
  leaves_start: { $lte: new Date },
  leaves_end:   { $gte: new Date }
});
corvid
  • 10,733
  • 11
  • 61
  • 130
  • This is based on the assumption that the values for the `leaves_start` and `leaves_end` fields are valid Date objects, not strings, something which the OP is yet to clarify. – chridam Oct 26 '15 at 16:18
0

I'm not sure if this will be helpful, but here's the code that I came up with:

THE RECORDS enter image description here

METHOD:

//monthyear = "10-2015"
//numOfDays = 31

getTowerLeaveData_LV: function(monthyear, numOfDays,tower, userid, username) {
        var selectedMonthYear = monthyear.split("-");
        var tempArr = new Array();
        var reArr = new Array()

        tempArr.push(username)
        reArr.push(username);

        LeavesCollection.find({associate_tower: {$in: tower}, leaves_approval_status: {$ne: 'Rejected'}, user_id: userid},{sort:{leaves_timestamp   :-1}},{fields: {_id:1,user_id:1,associate_id:1, associate_fullname:1,leaves_type:1,leaves_start:1,leaves_end:1, leaves_days:1}}).forEach(
          function(leaver) {
              for(var a=1; a!=numOfDays+1; a++) {
                var dateActive = selectedMonthYear[0] + "/" + a.toString() + "/" + selectedMonthYear[1];
                var res = dateCheck(leaver.leaves_start, leaver.leaves_end,dateActive);
                if(res == true) {
                    tempArr.splice(a, 0,[leaver.leaves_approval_status,leaver.leaves_type,leaver._id,leaver.associate_fullname,a]);
                }
              }
          });

        for(var a=1; a!=numOfDays+1; a++) {
          var temp = findKey(tempArr,a);

          if(temp != false) {
            reArr.push(tempArr[temp]);
          } else {
            reArr.push('null')
          }
        }

        return reArr;

    },

MISC JS FUNCTIONS:

function dateCheck(from,to,check) {

    var fDate,lDate,cDate;
    fDate = Date.parse(from);
    lDate = Date.parse(to);
    cDate = Date.parse(check);

    if((cDate <= lDate && cDate >= fDate)) {
        return true;
    }
    return false;
}



function findKey(array, search) {
  var theIndex = false;
  for (var i = 0; i < array.length; i++) {
    if (array[i].indexOf(search) > -1) {
        theIndex = i;
        break;
    }
  }
  return(theIndex);
}

OUTPUT IN ARRAY: enter image description here

EXPLANATION OF OUTPUT:

The items after the Name in the array is equal to the value of numOfDays(which is dates). If the program find a match date to the range between "leaves_start" and "leaves_end", it will return the array data from mongodb, if not, it will return "null".

Junel
  • 69
  • 3