Tips for finding documents in MongoDB using query filters

My website features a table where users can enter a word in a search field, prompting mongodb to search for matching words in specific objects and only return those results. The search text is included in the request query.

Although the following code handles pagination, it lacks the search functionality.

const result = await orders.aggregate([
      { $facet: {
        rows: [
          { $match: { status: {
            $in: ['received', 'packing', 'packed', 'fulfilled', 'rejected', 'withdrawn'],
          },
          } },
          { $skip: offsetPage * parseInt(req.query.rowsPerPage) },
          { $limit: parseInt(req.query.rowsPerPage) },
          { $project: {
            record: 1,
            status: 1,
            onPalette: 1,
            note: 1,
            grossTotal: 1,
            receivedLog: 1,
            arrivalDate: 1,
            partner: 1,
            location: 1,
          } },
        ],
        count: [
          { $count: 'count' },
        ],
      } },
    ]).toArray();

I wish to search within the "record" field, which contains numbers, and in the "partner.name" field, which contains strings.

If no search query is sent, or if the search query (req.query.filter) is an empty string, then return all data.

Answer №1

{ "_id" : 1, "location" : "Main Street",
  "in_stock" : [ "peaches", "kiwis", "pineapples" ] }
{ "_id" : 2, "location" : "Park Avenue",
  "in_stock" : [ "pineapples", "mangos", "strawberries" ] }
{ "_id" : 3, "location" : "Broadway",
  "in_stock" : [ "blueberries", "raspberries", "peaches" ] }
db.fruit.aggregate([
  {
    $project: {
      "store location" : "$location",
      "has peaches" : {
        $in: [ "peaches", "$in_stock" ]
      }
    }
  }
])
OUTPUT --
{ "_id" : 1, "store location" : "Main Street", "has peaches" : true }
{ "_id" : 2, "store location" : "Park Avenue", "has peaches" : false }
{ "_id" : 3, "store location" : "Broadway", "has peaches" : true }

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

What is the process for calculating the total sum of input values utilizing JavaScript?

My JavaScript skills are not perfect, and I'm struggling to calculate the total sum of values in the amount input boxes without refreshing the page. Can someone assist me with this challenge? Thank you. function Calculat ...

The concept of using the `map` method within a

Hi there, I could use some assistance with a tricky issue I'm facing. My current task involves rendering a cart object that includes product names, prices, and quantities. Each product can have its own set of product options stored as an array of ob ...

The optimal and most secure location for storing and retrieving user access credentials

After receiving a list of locations accessible to the session user from the server, I am seeking the ideal location to store these roles in Angular. This will allow me to determine whether or not to display specific routes or buttons for the user. Where ...

Tips for uploading arrays in Node.js´s:1. Use the `

Can someone help me with posting multiple arrays simultaneously? Here is what I am trying to achieve: { name:"John Snow", detail: [ {size: "M", total: 5, color: "red"}, {size: "S", total: 2, color: "bl ...

What is the best way to organize and structure a node.js project for modularity?

In the process of developing a node.js project, I am adhering to the class constructor pattern as shown below: function my_class(x,y){ this.x = x; this.y = y; } The foundation of the project lies within the main.js file. It is imperative that any ...

Extracting information from within Ajax's Jsonp

How can I retrieve data from the Ajax function(result)? Why isn't this app working? Please assist me. function star(a) { var res; $.ajax({ url: 'https://api-metrica.yandex.com/analytics/v3/data/ga?end-date=today&ids=ga%3A35 ...

I am struggling to send an email using PHP mailer with POST data

i'm facing challenges with integrating phpmailer and ajax. As a beginner in ajax, I still have some gaps in understanding the concept. When I directly run my php mailer script on a page with preset values, I can successfully send out an email. However ...

Retrieving pals from the API and showcasing them on the user interface

Currently, I am working on a project involving a unique Chat Application. While progressing with the development, I encountered an issue related to fetching friends data from the backend (node). Even though I can successfully retrieve the friends data in ...

How can one adhere to Angular's recommendation of "always using dots with ngModel" while working within isolate scopes?

Currently, I am working on developing an Angular application utilizing Bootstrap. To reduce the impact of Bootstrap on my HTML code, I have implemented two directives specifically for forms: form-control.js module.directive('formControl', func ...

Steps for capturing a screenshot of the canvas while utilizing the react-stl-obj-viewer component

I recently started using a component called react-stl-obj-viewer to display a 3D STL image. The rendering of the image itself is working fine. However, I encountered an issue when trying to move the rendered image around and implement a button for capturin ...

Is there a way to automatically select all checkboxes when I select contacts in my case using Ionic 2?

initializeSelection() { for (var i = 0; i < this.groupedContacts.length; i++) { for(var j = 0; j < this.groupedContacts[i].length; j++) this.groupedContacts[i][j].selected = this.selectedAll; } } evaluateSelectionStatus() { ...

The process of setting up a carousel for tables using jQuery

I can successfully implement jquery for an image carousel, but now I need to find a way to create a sliding table format. Any assistance on this matter would be greatly appreciated. Here is the code I currently have: <ul> <li><a style= ...

Ajax encounters difficulty in parsing JSON data

I have thoroughly researched similar questions on this topic, but none of them have provided a solution to my problem. My current challenge involves parsing JSON data that is being returned from a PHP script running on the server. I have already used JSON ...

defiant underscore refusing to function

I'm currently working on a text editor, but I'm facing an issue with the remove underline functionality that doesn't seem to be working as expected. For reference, you can check out a working code example here: jsfiddle Below is the part of ...

Ensure that each item rendered in a VUE.js v-for loop is distinct and not repetitive

I have obtained a JSON formatted object from a Web API that contains information about NIH funding grants. Each grant provides a history of awards for a specific researcher. My goal is to display only the latest award_notice_date for each unique project ...

Issue: Unable to open port (GetCommState) : Error code 1 not recognized - Utilizing Nodejs, express, SerialPort

I am currently attempting to establish a connection between a fiscal printer with serial input and nodejs. I am utilizing the SerialPort module, but encountering difficulty in establishing the connection. The console is displaying the following error messa ...

The Vuex mutation does not execute synchronously and does not resolve as a promise

My vuex mutation doesn't work synchronously as expected. Here is the code: mutations: { computeStatusData(state, status) { if (status.active !== true) { return } const started = new Date(status.startedAt); started.setHour ...

Saving user sessions in Express.js for a complete MERN Stack web application

I've been struggling to save a user's email in the session for my express.js application. However, every time I attempt to do so and call another function, the session remains undefined. My goal was to store it in the browser without storing each ...

Mongoose transforms the outcome of the create() function

Is there a way to exclude certain fields from the result of a Mongoose create() command for a new document in a collection? Currently, I am seeking to avoid returning all fields of an object, particularly the password field which consists of hash and salt ...

Guide on utilizing TypeScript interfaces or types in JavaScript functions with vscode and jsdocs

Is there a way to utilize types or interfaces to provide intellisense for entire functions or object literals, rather than just function parameters or inline @type's? For example: type TFunc = ( x: number ) => boolean; /** * @implements {TFunc} ...