MongoDB has encountered an error while attempting to combine two disparate conditions

I need to run a MongoDB query using JavaScript. Specifically, I am looking to retrieve documents based on two different criteria.

The first condition is as follows:

        $or: [
          { "users.username": user.username },
          { buyer: user.username }
        ]

The second condition is:

$or: [
          { description: { $regex: req.query.q } },
          { buyer: { $regex: req.query.q } },
          { category: { $regex: req.query.q } }
        ]

To combine these two conditions into a single query, the code snippet used is:

const expenses = await db
    .collection("expenses")
    .find({
      $expr: {
        $or: [
          { "users.username": user.username },
          { buyer: user.username }
        ]
      },
      $expr: {
        $or: [
          { description: { $regex: req.query.q } },
          { buyer: { $regex: req.query.q } },
          { category: { $regex: req.query.q } }
        ],
      },
    })

However, running this query results in the following error message:

MongoServerError: Unrecognized expression '$regex'

Can anyone provide guidance on how to resolve this error? Your assistance is greatly appreciated.

Answer №1

It seems there may be some confusion between the mongo query language and the aggregation pipeline operators. Additionally, there appears to be an error in building the JavaScript object.

Distinguishing MQL from Aggregation Pipeline Operators

The $expr operator serves the purpose of allowing aggregation expressions within the query language, as mentioned in the documentation.

This operator permits the utilization of aggregation expressions in the query language context.

$expr is not merely a subcategory of query operators; it introduces an entirely distinct set of operators.

Illustrative examples include:

  • The $eq operator is specifically applicable within $expr.
  • References to another field's value (using $) are only valid inside $expr.
  • Various operators exhibit different behavior as part of aggregation than query operators do, for instance $in versus $in

While the mongo query language includes a $regex operator, no equivalent aggregation pipeline operator exists.

Aggregation employs operations like $regexFind, $regexMatch, and $regexFindAll; refer to https://www.mongodb.com/docs/manual/reference/operator/aggregation

Constructing Javascript Objects Properly

The initial argument required by the find method is a javascript object. In your code snippet, you have provided:

    {
      $expr: {$or: [
          { "users.username": user.username },
          { buyer: user.username }
      ]},
      $expr: {$or: [
          { description: { $regex: req.query.q } },
          { buyer: { $regex: req.query.q } },
          { category: { $regex: req.query.q } }
      ]}
    }

It's worth noting that this object features 2 fields bearing identical names, '$expr'. While BSON technically allows this, JavaScript/JSON prohibit such duplicate names, thereby causing the second declaration to overwrite the first.
Thus, the actual query being transmitted becomes:

    {
      $expr: {$or: [
          { description: { $regex: req.query.q } },
          { buyer: { $regex: req.query.q } },
          { category: { $regex: req.query.q } }
      ]}
    }

If you need to incorporate multiple $or clauses, they must be amalgamated using a superior-level operator, akin to:

{$and: [
      {$or: [
          { "users.username": user.username },
          { buyer: user.username }
      ]},
      {$or: [
          { description: { $regex: req.query.q } },
          { buyer: { $regex: req.query.q } },
          { category: { $regex: req.query.q } }
      ]}
]}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Preventing form submission with JavaScript by implementing multiple validation checks

Preventing a form from submitting when validation returns false is possible. Here's an example: <form name="registration" action="registration.php" onsubmit="return validate()"> <!-- some inputs like: --> <input type="text" id="us ...

What are the steps to update your profile picture using Angular?

In my Angular 6 application, I am implementing an image upload feature with the following code: Html: <img [src]="url ? url : 'https://www.w3schools.com/howto/img_avatar.png'"> <br/> <input type='file' (change)="onSelec ...

Dimension of the element that has been positioned absolutely

One of my challenges involves working with an absolutely positioned div element (.tooltip) containing another div (.text) that has text with a set max-width. The issue arises when the left property of .tooltip is too large, causing its width to shrink du ...

Use Angular.js to perform navigation after clicking the "Ok" button on a confirmation box

I encountered a problem with my requirement. I need a confirm box to appear when the user attempts to navigate to the next state/page. Only if the user clicks on the "Ok" button should it proceed to the next state; otherwise, it should stay as it is. Below ...

Leveraging Enjoyhint within nextJS

I am attempting to create a code tour using EnjoyHint, but encountered an error after installing the xbs-enjoyhint library. The error reads: Server Error - ReferenceError: CanvasRenderingContext2D is not defined. This issue is within the jquery.enjoyhint ...

I'm having trouble retrieving my variable within the socketcluster's socket.on function

How can I store the value of msg in the variable sample when sample is not accessible inside the callback function? import { Injectable } from '@angular/core'; import * as socketCluster from 'socketcluster-client'; @Injectable({ pro ...

Traversing JSON data structures regardless of missing keys

Here is a JSON containing some data: { "results":[ { "name":"Sydney Showboats", "photos":[ { "photo_reference":"Pic062" } ] }, ...

What is the best way to transmit data to a PHP script using AJAX?

I'm facing an issue with my basic ajax script not running. The code I have should work fine. The ajax script is: <html> <head><title>Testing ajax</title> <script type="text/javascript"> function ajax() { ...

Steps for creating a basic table filter using jQuery

What is an efficient way to create a basic table filter using jQuery without pagination requirements? I want to retrieve data from a database and display it as a list. I would like to avoid using plugins and instead opt for concise code snippets. For ...

Click on the hyperlinks one by one that trigger ajax events

There is a feature on the popular social media platform reddit.com where you can load more comments by clicking a link. I understand that comments may be hidden for performance reasons, but I would like to automatically expand all comments without having t ...

Combining objects while utilizing SetState within a loop: a guide

Inside my component, the state is structured as follows: class MainClass constructor(props) { super(props); this.state = { form: { startDate:"1/11/2020", endDate:"5/11/2020", .... }, ...

I am having trouble with my quiz function as it only checks the answer correctly for the first question. Does anyone have suggestions on how to make it work for

Currently, I'm tackling a quiz project that was assigned to me during my bootcamp. My focus right now is on the checkAnswer function, which evaluates the answer selected by the player. const startButton = document.querySelector(".start") as ...

Issues in the d3.js chart

I'm facing an issue with some incorrect lines appearing in my d3.js chart. Strangely, the problem seems to disappear when I switch tabs on Chrome and return to the chart's tab. It's puzzling to figure out the root cause of this issue, so I ...

The time selector does not appear in the v-date-picker widget

I need help figuring out how to select a time range using v-date-picker on vCalender within my Vuetify project. Despite setting the mode of v-date-picker to dateTime, I am unable to find an option to choose the time along with the date. Is there something ...

How do I incorporate pagination into a PL-SQL dynamic content table in Oracle Apex?

I've successfully created a PL-SQL dynamic content report in Oracle Apex, but I'm struggling with implementing pagination. With too many rows to display at once, adding pagination will greatly enhance the user experience. Here is a snippet of my ...

Vue.js: Error 404 - POST request endpoint not found

My goal is to access my Quasar application from other devices connected to the Local Area Network. I have successfully run the app on these devices, but I encountered an error POST http://10.0.0.20:8080/MyComposer/?submitId=3 404 (Not Found) when trying to ...

Seeking guidance on capturing the correct error message when using JSON stringify?

Imagine I have an object structured as follows var obj = { "name": "arun" age } After attempting JSON.stringify(obj), it results in an error due to the improper structure of the obj. I am interested in capturing this error displayed in the console and pr ...

An absence of data causes the function to malfunction

One of the components in my application is responsible for rendering select elements on the screen, allowing users to dynamically order data. The initial state is as follows: state = { sortBy: [ { author: 'asc' } ] }; In this s ...

React App with Material UI V1-beta Integration

I just installed the Create React App example from Material-UI.com. curl https://codeload.github.com/callemall/material-ui/tar.gz/v1-beta | tar -xz --strip=2 material-ui-1-beta/examples/create-react-app Upon installation, I encountered the following erro ...

Rendering content conditionally using react technology

There is a functional component that receives two items as props. The properties can have values like `undefined`, `""`, `null`, `"null"`, or a valid string (e.g. `"test"`). The goal is to conditionally render these props based on their values. If both ` ...