-1

This is my model:

UserModel = mongoose.Document & {
    username: string,
    password: string,
    records: Record[]
};
Record: {
    name: string;
    date: Date;
}

Query:

    const date = new Date();
    const lastDate = new Date(date.getTime() - (30 * 24 * 60 * 60 * 1000));
    UserModel.find({ "records" : { "$elemMatch": {  "date" : { "$gte": lastDate } } }}, (err, userRecords: any) => {
     if (err) {
         return res.json({
             "status": "error",
             "detail": err
         });
     }
     return res.json({
         "records": userRecords
     });
   });

This query returns all records, rather than records just from last 30 days. I am unable to locate where I am going wrong.

Edit: Even after using "lastDate.toISOString()" inplace of "lastDate" above, I still get all the results back.

Edit: Tested few other solution, like using "$filter", but still I get all records back.

Don
  • 1,334
  • 1
  • 10
  • 18
  • `.find()` queries do not "filter" the array content returned. That task belongs to [`$filter`](https://docs.mongodb.com/manual/reference/operator/aggregation/filter/) – Neil Lunn Nov 09 '17 at 05:33
  • Check the format in which the `date` is stored in `Records` document. In Mongo if filter conditions for fields are not matching the format, it returns entire collection – Abhishek Nov 09 '17 at 05:46
  • @Abhishek its stored as format Date in document – Don Nov 09 '17 at 05:48
  • If you can't help, it fine.You don't need to be vigil anti. I did try whatever you posted as duplicate, and it didn't work. Looks at my edit. – Don Nov 09 '17 at 05:54

1 Answers1

0

You need to convert the date to ISO format in which it stored in DB then it will work.