Unable to execute query with $gt and $size in Mongoose

Below is my mongoose query along with the router:

router.get('/reportsRegular', function(req,res,next){
  Question.find({reports: {$size: {$gt: 0}}, checked: false}).sort({reports: -1}).limit(20).exec(function(err,results){
    console.log(results)
    res.render('reports', {type: 'regular', user: req.user, reports: results})
})

I encountered an issue with the first find condition. When I change $gt to 1 instead of using it for cases with more than one, it works fine. However, it fails in scenarios where there are multiple items, so I need to use $gt.

Here is a sample JSON document that should match but is not being found:

{
  _id: new ObjectId("6212e77aa1e98ae3282a61e6"),
  title: 'TOMATOOOOOO',
  text: '<p>AAAAAAAAAAAAAAAA</p>',
  authorUsername: 'SweetWhite',
  dateCreated: 2022-02-21T01:14:34.901Z,
  answers: [],
  likes: [0],
  dislikes: [0],
  tag: 'Languages',
  views: [1, 'SweetWhite'],
  reports: ['SweetWhite'],
  checked: false,
  reportsNested: [],
  __v: 0
}

It should be found as the size of the reports array is greater than zero and the checked value is false. What am I missing here?

Thank you!

Answer №1

You must have $expr. Also, update the filter to be:

{
  $expr: {
    $gt: [
      {
        "$size": "$reports"
      },
      0
    ]
  },
  checked: false
}

Example Mongo Playground Link

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

Retrieve the URL of an embedded image using discord.py and verify its presence within a JSON file

Currently, I am attempting to verify the existence of a specific URL found in message.embeds[0].image.url within my JSON file. Below is the code snippet that I am using: import discord import json from datetime import datetime bot = commands.Bot(command_p ...

Should I utilize Sockets or Ajax for my project?

My Login Script Journey I have a goal in mind - to create a login script using Nodejs. I am currently exploring the options of utilizing sockets or ajax posts for this task. My Progress So Far I have Nodejs installed and have referenced this code in my ...

Grouping by another field, an aggregation query calculates the total sum of two integer arrays

I just started learning about MongoDB and I'm facing an issue. Within my document, there is a fixed-size integer array that I need to calculate the sum of. Is it possible for MongoDB to sum two integer arrays in a query grouped by another field, such ...

Purge ajax result upon completion of server operation

I'm currently working with an AJAX code that takes input from a radio form. The server code, upon satisfying a specific if() condition, redirects to another page on my site, such as dashboard.php! However, upon redirection, I am still seeing the rad ...

Tips for using ng-repeat in AngularJs to filter (key, value) pairs

I am trying to achieve the following: <div ng-controller="TestCtrl"> <div ng-repeat="(k,v) in items | filter:hasSecurityId"> {{k}} {{v.pos}} </div> </div> Code snippet for AngularJs: function TestCtrl($scope) { ...

React Higher Order Components (HOCs) are functioning correctly with certain components but not

I have encountered an issue where using a Higher Order Component (HOC) to bind an action to various types of elements, including SVG cells, results in unintended behavior. When I bind the onClick event handler normally, everything works fine, but when I ap ...

Tips on altering a predetermined input text value using JavaScript

I have a question about using JavaScript. I am currently developing a tax calculation system. function calculateTax(){ var invoiceValue = document.getElementById("invoicevalue"); var ppn = document.getElementById("ppn"); var pph = document.get ...

Comparing two datetime objects with time zone offsets in JavaScript: How to determine if one is greater than or less than the other?

So I'm faced with a situation where I need to compare two dates where the first date is 05.01.2008 6:00 +5:00 and the second date is 05.01.2008 7:00 +5:00 I'm struggling to find a way to convert these datetimeoffsets into a specific forma ...

Substitute a JSONP API call using $.ajax() with a direct server-to-server API call

My javascript application utilizes an ajax function that has the following structure: $.ajax({ url: apiURL, dataType: 'jsonp', success: function(data) { if (data.ok) { //perform actions }}}); Everything was working perfectly until I ...

ReactJS: error occurs when trying to fetch data and encountering issues with reading properties

I am currently attempting to initiate an API call (a GET request) in order to download a document. However, I am encountering an error when making the API call: TypeError: Cannot read properties of undefined (reading 'payload') const printPin ...

Generating div elements dynamically and applying styles

Generating a div dynamically and adding style to it var newDiv = document.createElement('div'); newDiv.setAttribute("id","dynamic-div"); document.body.appendChild(newDiv); // Simulating dynamic ajax content loading $(document).ready(function () ...

There seems to be an issue with Jquery Ajax retrieving information from an ASP.NET WEB API

Recently, I have started delving into APS.NET MVC WEB API programming. My current dilemma involves creating an ASP.NET WEB API project with the following code: public class ValuesController : ApiController { // GET api/values public IEnumerable& ...

The custom $compile directive is selectively applied within the same scope

Thank you for taking a look. Let's get right into it: A JSON object contains HTML links with ng-click attributes, using ng-bind-html, and securing the HTML with $sce's trustAsHtml. Additionally, I've implemented a custom angular-compile dir ...

Using the THIS keyword in JQUERY for functions without an action: a guide

Is there a way to dynamically set the widths of table elements based on their parent's data-attribute value? For example, if a parent has percent="10", I want the child element to have a width of 10%. How can this be accomplished? To illustrate, here ...

What is the process for adding texture to a model that has been imported using OBJLoader?

I've been immersed in my little project using three.js, but I'm facing a challenge with mapping textures on objects loaded by THREE.OBJLoader. Interestingly, there are no issues with three.js built-in geometry. I find myself quite perplexed... / ...

Ensure that the Promise is resolved upon the event firing, without the need for multiple event

I'm currently working on a solution where I need to handle promise resolution when an EventEmitter event occurs. In the function containing this logic, an argument is passed and added to a stack. Later, items are processed from the stack with differe ...

Encountering a React clash while integrating Material UI

Upon trying to utilize the AppBar feature in Material UI version 0.16.6, I encountered the following error: Uncaught Error: addComponentAsRefTo(...): Only a ReactOwner can have refs. You might be adding a ref to a component that was not created within a c ...

What is the process for adding an additional level to an Object for an item that is not predefined?

The primary concern at hand is as follows: Retrieve JSON data from the server Populate a form with the data Serialize the form Create a JSON object with the correct structure Send the JSON object back to the server I am facing challenges specifically on ...

The button's onclick function is not triggering with just one click

I am having trouble with a JavaScript function not being called on the first click. I have to click the button multiple times for it to execute. Here are the methods I have attempted so far: <a href="javascript:delete_todo(4);void(0)"><img border ...

Extracting data from a MongoDB array

I need help querying an array in MongoDB Sample Data I have data with multiple arrays of fields containing dynamic field names that are not mandatory and are randomly positioned. I want to extract a specific title and its value for all the fields. { ...