I am trying to do a query by 2 parameters on a mongoDb database using Mongoose. I need to query by who the document was created by and also a subdocument called events which has a date. I want to bring back all documents within a timeframe.
My query looks like this.
var earliest = new Date(2018,0,3);
var latest = new Date(2018,0,4);
Goal.find({createdBy:userId,'events.date':{$gte: earliest, $lte: latest}})
.exec(function(err,doc)){ //do stuff}
The document below is what was returned. I get everything in my database back and my date range query isn't taken into account. I'm new to Mongodb and I don't know what I am doing wrong.
[
{
_id: "5a4dac123f37dd3818950493",
goalName: "My First Goal",
createdBy: "5a4dab8c3f37dd3818950492",
__v: 0,
events:
[
{
_id: "5a4dac123f37dd3818950494",
eventText: "Test Goal",
eventType: "multiDay",
date: "2018-01-03T00:00:00.000Z",
eventLength: 7,
completed: false
},
{
_id: "5a4dac123f37dd3818950495",
eventText: "Test Goal",
eventType: "multiDay",
date: "2018-01-04T00:00:00.000Z",
eventLength: 7,
completed: false
},
{
_id: "5a4dac123f37dd3818950496",
eventText: "Test Goal",
eventType: "multiDay",
date: "2018-01-05T00:00:00.000Z",
eventLength: 7,
completed: false
}
],
startDate: "2018-01-04T00:00:00.000Z",
createdOn: "2018-01-04T00:00:00.000Z"
}
]