Hello guys, I’m trying to perform a search operation for a data model below: The query is to return every property where the number of guests matches the number of guests specified in the query for example 3, and the location should match the provided location in the query, for example, Brooklyn in this case.
I have tried the regex expression like this:
let query = {};
if (req.query.location) {
query.location = { "$regex": req.query.location, "$options": "i" };
}
if (req.query.noOfGuests) {
query.guests_included = { "$where": Number(req.query.noOfGuests) };
}
const searchResults = await Listing.find(query);
This query returns a Cast Error like so below:
{
"stringValue": "\"3\"",
"valueType": "number",
"kind": "number",
"value": 3,
"path": "guests_included",
"reason": null,
"name": "CastError",
"message": "Cast to number failed for value \"3\" (type number) at path \"guests_included\" for model \"Listing\""
}
This is a sample data:
{
"_id": {"$oid":"64250f9a01625ffc9d744ac9"},
"name": "Stunning 1 Bedroom Apartment in Holborn, London",
"description": "Located in the heart of Holborn, this beautiful apartment is the ideal base to explore central London. The apartment comprises a large open-plan living space, a fully equipped kitchen, a spacious bedroom with a king bed, and a bathroom with complimentary toiletries and fluffy towels. There is space for up to 3 guests with the use of the sofa bed. In the heart of the city, you are within walking distance of many of London's most famous attractions - the ideal base for your trip!",
"beds":{"$numberInt":"2"},
"numReviews":{"$numberInt":"0"},
"rating":{"$numberInt":"5"},
"bathrooms":{"$numberInt":"1"},
"amenities":["Kitchen", "TV", "Wifi", "Washer", "Air conditioner"],
"price":{"$numberInt":"4498"},
"guests_included":{"$numberInt":"3"},
"images":["https://a0.muscache.com/im/pictures/prohost-api/Hosting-810793423389859668/original/6c93c696-0e4c-48fb-ad06-fde74dc946d4.jpeg?im_w=1200","https://a0.muscache.com/im/pictures/prohost-api/Hosting-810793423389859668/original/381a0099-2409-4be8-b1f9-f5e4b954a601.jpeg?im_w=720","https://a0.muscache.com/im/pictures/prohost-api/Hosting-810793423389859668/original/a04a5821-fc07-4122-8c20-c373db7f1794.jpeg?im_w=720","https://a0.muscache.com/im/pictures/prohost-api/Hosting-810793423389859668/original/9b7a1e06-bd86-475c-bb79-79e8ee469849.jpeg?im_w=720","https://a0.muscache.com/im/pictures/prohost-api/Hosting-810793423389859668/original/a2c5daa3-866f-4c75-b014-6c35e1727038.jpeg?im_w=720"],
"reviews":[],
"createdAt":{"$date":{"$numberLong":"1680150426657"}},"
updatedAt":{"$date":{"$numberLong":"1680150426657"}},
"__v":{"$numberInt":"0"},
"address":{"street":"Brooklyn, NY, United States", "suburb":"Brooklyn", "government_area": "Bushwick", "market":"New York","country":"United States"},
"location":"Brooklyn"}
I have read the MongoDB documentation and couldn’t find a way around this yet.