Kay
Kay

Reputation: 19660

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""

Upvotes: 4

Views: 9262

Answers (1)

Rashad Ibrahimov
Rashad Ibrahimov

Reputation: 3309

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.

Upvotes: 6

Related Questions