I am creating a search bar using react to find several data fields in mongodb document. I send a keyword from a frontend to NodeJS api to search documents containing that keyword. So far I can search any string value fields. But I want to search createdAt date value also using same search.
For example I want to get all documents createdAt using "2021-26-11" this string value. Below is my mongoose condition
var condition = title ? { $or: [{ title: { $regex: new RegExp(title), $options: "i" } }, { author: { $regex: new RegExp(title), $options: "i" } },{ createdAt: { $regex: new RegExp(title), $options: "i" } }] } : {};
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>
CodePudding user response:
Or you could get the timestamp of created date and in the search put a datepicker and use that timestamp to compare, won't have deal with regex
CodePudding user response:
var condition = title ? { $or: [{ title: { $regex: new RegExp(title), $options: "i" } }, { author: { $regex: new RegExp(title), $options: "i" } },{ createdAt: new Date(title) }] } : {};
You could try this way, But make sure to check
- your
title
is valid date format or not. - If it's date then make sure to add Greather then that Date and Less than the end of that date - conditions.