0

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"
  }
]
  • `new Date(2018,0,3)` here 2018 is year and zero is month and 3 is day so how month is zero may be this is an issue here. console these two statements `var earliest = new Date(2018,0,3); var latest = new Date(2018,0,4);` – Manjeet Thakur Jan 05 '18 at 06:24
  • Possible duplicate of [Retrieve only the queried element in an object array in MongoDB collection](https://stackoverflow.com/questions/3985214/retrieve-only-the-queried-element-in-an-object-array-in-mongodb-collection) – s7vr Jan 05 '18 at 11:32

1 Answers1

1

There is a difference between matching documents and matching "elements of an array". Your document already contains the whole array, even the values that don't match your array filter criteria. But since your document match criteria matches, the whole document is returned (with all the array entries).

If you just want the matching "elements" then use .aggregate() instead. An example on how to use aggregate for such a task is available at Mongodb find inside sub array

Ishan Thilina Somasiri
  • 1,179
  • 1
  • 12
  • 24