0

I have this date given by a date picker widget:

let targetDate = '2019-01-12';

All my documents have a createtAt date generated by timestamps:

"createdAt": "2019-01-12T21:49:05.546Z"

I want to get all documents that field createdAt matches with my given date. I tried using $elemMatch:

const allDailies = await Daily.find({ createdAt: { $elemMatch: dateTarget } });

const allDailies = await Daily.find({ createdAt: { $elemMatch: { from: dateTarget, to: dateTarget} } });

And no one works, how can I do this query? Actually I can't modify my Schema :(

EDIT:

router.get('/daily/:date', async (req, res) => {
  try {
    const targetDate = new RegExp(`^${req.params.date}`);
    const allDailies = await Daily.find({ createdAt: { $regex: targetDate } });
    console.log('Dailies', allDailies);
    return res.json({ allDailies });
  } catch (error) {
    return res.sendStatus(httpStatus.INTERNAL_SERVER_ERROR);
  }
});

It returns a 500 error

maudev
  • 974
  • 1
  • 14
  • 32

2 Answers2

0

Convert your targetDate to the same type as createdAt and use it on query as tatgetDate. Not dateTarget as you use it now (you typed it wrong).

dimitris tseggenes
  • 3,031
  • 2
  • 16
  • 23
0

You have to convert your target date in to ISODate format. But this will be taken care by mongoose by default so.. What you want to do is change your query like this

Model.find({createdAt:{$gte:params.frm, $lte:params.to}},callback);

or if you want to just give a single date try like this

Model.find({createdAt:dateTarget},callback);
ALPHA
  • 1,135
  • 1
  • 8
  • 18
  • also note that your target date formate is ok to be used by mongoose to make the conversion implicitly – ALPHA Jan 13 '19 at 02:35