Search for data in Mongoose by utilizing a query object that has been obtained from a query string

After extracting and parsing a querystring from a URL, I am able to map it into an object structure like this:

{ '$and': [ { length: { '$gt': '2' } }, { length: { '$lt': '55555' } } ] }

This object is stored in a constant called q.

Now, if we were to construct a Mongoose find query based on the mapped object, it might look something like this:

  Schema.find(q, function (err, results) {
    if (err) {
      console.log(err);
    }
     else {
       console.log(results);
     }
   });

However, the above code returns empty lists ([]). When logging q to the console, the following output is displayed:

{ '$and': [ { length: [Object] }, { length: [Object] } ] }

Answer №1

--update-- when working with your database, make sure to treat length as a number

db.collection.find({
  "$and": [
    {
      length: {
        "$gt": 2 // not '2'
      }
    },
    {
      length: {
        "$lt": 55555 // not '55555'
      }
    }
  ]
})

https://mongoplayground.net/p/aJVF9QfDeKy

Answer №2

 const query = { '$and': [ { length: { '$gt': '2' } }, { length: { '$lt': '55555' } } ] }

// Converting string keys to integers

query['$and'].map(function(obj) {

    for(var prop in obj.length){
        if(obj.length.hasOwnProperty(prop) && obj.length[prop] !== null && !isNaN(obj.length[prop])){
            obj.length[prop] = +obj.length[prop];   
        }
    }
});

console.log(query)

Schema.find(query, function (error, results) {
    if (error) {
      console.log(error);
    }
    else {
      console.log(results);
    }
});

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

Click event not triggered when transitioning to Service section in Thinkster tutorial

I've been following a tutorial on MEAN stack development () and I encountered an issue after incorporating Angular Services. For some reason, the function incrementUpvotes stopped working and I'm struggling to identify the cause. Since I'm r ...

What is the best way to retrieve the value of the "Observer" object?

I am a user of Vue.js and I have the following data in this.suspendedReserveMemo: this.suspendedReserveMemo [__ob__: Observer]650: "memo3"651: "memo4"652: ""653: ""654: ""655: ""656: ""657: ""658: ""659: ""660:""661: ""662: ""length: 663__ob__: Observer {v ...

Is there a way to determine the percentage between two specified dates?

If I have a specified start and end date, I am interested in knowing the progress percentage achieved from the start date up to the current date compared to the end date. To put it simply: I would like to determine how far along I am towards the end date i ...

Struggling to match the IDs of two objects in node.js with the objects retrieved from MongoDB

Upon opening a webpage from my browser, the following code snippet runs. It queries all users and removes the user object who is querying it. To achieve this, I am comparing their _id's field, which is generated by default in MongoDB and is always un ...

Easily conceal and reveal elements using Svelte in a straightforward manner

I'm looking for a straightforward method to hide and show an element using a button in Svelte. Can someone guide me on how to achieve this? Additionally, I'm curious if it's easier to accomplish this task with vanilla JavaScript. ...

What is the best way to retrieve an object instead of an array?

When attempting to retrieve a JSON Object, I unexpectedly received an array instead. My query is based on the primary key, so I anticipate only one result. This is my current method : router.get("/student_info/:id", (req, res, next) => { connecti ...

Utilize AngularJs and JavaScript to upload information to a JSON file

Exploring the realm of Angular JS, I am on a quest to create a CRUD form using AngularJs and Json with pure javascript without involving any other server side language. The script seems to be functioning well but is facing an obstacle when it comes to writ ...

Obtaining NodeJS from a mysterious subdirectory

-- plugins ---- myplugin1 ------ core ---- myplugin2 ------ core If this represents the directory structure, is there a method to import all core directories from plugins without specifying the specific plugin names like myplugin1? require('/plugins ...

Capturing user input in HTML and passing it to JavaScript

I have a good grasp on how to implement input in HTML to execute JavaScript functions that are defined in the same directory as the HTML file. For example: <input type="button" value="Submit" onclick="someFunc(500)" > When the button is clicked, th ...

Discover the method for extracting the value from an array that has been transferred from a php script

So here's the situation - I have a text file containing data. The first step is to convert the content of the text file into an array. $lines = file($filename); Next, the data is sent back to the client (the $filename is determined through ajax). ...

Updating the list in React upon form submission without requiring a full page refresh

Currently, I have a list of data being displayed with a specific sort order in the textbox. Users are able to modify the order and upon clicking submit, the changes are saved in the database. The updated list will then be displayed in the new order upon pa ...

Is the memory usage of node.js proportional to the number of concurrent requests, or is there a potential memory leak?

Running the following node.js code: var http = require('http'); http.createServer(function(req,res){ res.writeHead(200,{'Content-Type': 'text/plain'}); res.write("Hello"); res.end(); }).listen(8888); Upon starting the server ...

How can dependencies be conditionally imported in a module that is shared between React (Next.js) and React Native?

I am looking to create a shared Typescript module that can be used in both a React (Next.js) web app and React Native mobile apps. This module will be responsible for managing communication with the backend (Firebase) and handling state management using t ...

Dynamic loading of tinymce in progress

When tinymce is loaded in the head and before dom, everything works fine. However, if I attempt to load the JavaScript with ajax using jquery.getScript(), it doesn't work. I initialize tinymce when the user clicks the content area, so the dom must be ...

What is the specific table element compatible with Polymer3?

I stumbled upon iron-data-table (), but it relies on bower which is used in Polymer2. However, I am working with npm in Polymer3. Is there a suitable table element or an alternative solution compatible with Polymer3? ...

Using React Bootstrap, you can ensure that only a single collapse opens at a time when rendering it with a map function. This allows you to display

When a user clicks on the "View Tasks" button, I want to display the relevant tasks specific to that user. However, currently all React Bootstrap Collapse Components open up and show tasks for every user instead of just one. This issue arises because the o ...

Add the child's input query first and then concentrate on it

I have successfully appended a div with a child input, but I am facing an issue where the newly appended input is not getting focused when added. $(document).ready(function() { var max_fields = 10; //maximum input boxes allowed var wrapper ...

Choose the current parent item using Angular's ng-selected and $index

http://plnkr.co/edit/fwwAd4bn6z2vxVN2FUL7?p=preview On the Plunker page linked above, I am trying to achieve a specific functionality. I would like the 3 dropdown lists to display values A, B, and C initially. When a 4th dropdown option is added, it shoul ...

Is there a way for me to receive a success message when I successfully set data in Firebase?

I want to retrieve the orderId after successfully adding an order to the Realtime database using angularfirestore. What should I use after set() method to return the orderId? The structure of my order object is as follows: const orderObj: Order = { pay ...

Retrieving the name of the currently active express middleware function

Greetings to all! I have been an avid reader for a long time, but this is my first time reaching out with a question. My inquiry pertains to dynamically accessing function names in Express ^4.17.1. Despite thorough research on both the internet and the exp ...