Need help performing a string and integer query

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





"amenities":["Kitchen", "TV", "Wifi", "Washer", "Air conditioner"],








"address":{"street":"Brooklyn, NY, United States", "suburb":"Brooklyn", "government_area": "Bushwick", "market":"New York","country":"United States"},


I have read the MongoDB documentation and couldn’t find a way around this yet.

Okay! I just fixed this using $in like so below:

let query = {};
  if (req.query.location) {
    query.location = { "$regex": req.query.location, "$options": "i" };
  if (req.query.noOfGuests) {
    query.guests_included = { $in: Number(req.query.noOfGuests) };

  try {
    const searchResults = await Listing.find(query);
  } catch (err) {

If anyone else has a better method to reduce computation time and increase efficiency, please share. Thanks!

You should absolutely never use $where. $in works but you only need it when you want to match one of several possible values, when it’s a simple equality match just use $eq or implicit equality (that is {a:5} is the same as {a:{$eq:5}}.

Thank you Asya, this solves it.

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.