Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Node.js and Mongoose - Cast to date failed for value (filtering created_at dates)

Im creating a search endpoint that will filter the results via a date range.

http://0.0.0.0:3000/api/v1/transactions/search?endDate=2018-10-03T14:07:03.382Z

So the above, wants to search all transactions up to and equal the created_at date.

console.log(req.query.endDate) // 2018-10-03T14:07:03.382Z

This is part of the query i build

created_at = {
   gte: startDate,
   lte: endDate,
};

    let query = {
    ...query,
    created_at
}

const transactions = await Transaction.find(query);

This is what my query string looks like

{ created_at: { lte: '2018-10-03T14:07:03.382Z' } }

However i get the following error.

Cast to date failed for value "{ lte: '2018-10-03T14:07:03.382Z' }" at path "created_at" for model "Transaction""

like image 923
Kay Avatar asked Oct 27 '25 08:10

Kay


1 Answers

Short answer: It should be $lte, not lte.

Long answer:

There is pretty good tutorial what you need to know about Working With Dates in mongoose.

Let's say you have a schema where you have declared field with type of Date.

When you create a document, Mongoose will cast the value to a native JavaScript date using the Date() constructor.

An invalid date will lead to a CastError when you validate the document.

Because of missing $ sign, your query is accepted like "Find me transactions where created_at is an object equal { lte: '2018-10-03T14:07:03.382Z' }".

Mongoose will try to convert this value to date.

new Date({ lte: '2018-10-03T14:07:03.382Z' });

Obviously it's not a valid date, and this expression will fail with CastError.

like image 130
Rashad Ibrahimov Avatar answered Oct 28 '25 21:10

Rashad Ibrahimov



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!