The MongoDB query isn't functioning properly as the Match operation is returning an array with no elements

I am currently facing an issue with creating an aggregation pipeline. Everything seems to be working fine in the code until it reaches the $match section, which returns nothing. Here is the snippet of my code:

    var userId = req.params.UserId
    const measure = await Measure.aggregate([
        {
            $project: {
                user: 1, creationDate: 1, WaterConsumption: 1
            }
        }, 
        {
            $match: {
                user: userId
            }
        },
        {
            $group: {
                _id: {
                    $dayOfMonth: "$creationDate"
                },
                waterConsumption: {$sum :  "$WaterConsumption"}
            }
        }
    ]);
    return res.json({measure})

The data I am trying to filter through is as follows:

{
  "measures": [
    {
      "creationDate": "2021-03-19T10:25:05.674Z",
      "_id": "605870bffa87a605bf2a983a",
      "avgPower": 8241,
      "WaterConsumption": 22,
      "avgTemperature": 45,
      "shower": "5fb56ce7734b7e04b9c97c9b",
      "user": "5f6cb0496a8c5a0deaa1a746"
    },
    {
      "creationDate": ""2021-03-17T10:25:05.674Z"",
      "_id": "605870ebfa87a605bf2a983c"",
      "avgPower": 4300,
      "WaterConsumption"': 32,
      'avgTemperature': 28,
      'shower':"5fb56d04734b7e04b9c97c9c",
      'user'': '"5f6cb0496a8c5a0deaa1a746"''
    }...
  ]

Despite having the correct user ID value and formatting, the $match stage does not seem to be functioning correctly. The $group section works perfectly fine. Even after attempting to modify $match to $match:{user: req.params.UserId}, the result remains an empty array.

Answer №1

Have you ever encountered difficulties matching a string with ObjectId? This could be the reason why your $match is not functioning as expected.

If you need more information on ObjectId, you can visit this link: ObjectId

For a working demonstration using ObjectId, check out this link: https://mongoplayground.net/p/Oz95gFwvp9X

const mongodb = require('mongodb');
const ObjectID = mongodb.ObjectID;
const userId = ObjectID(req.params.UserId); // Convert your userid to ObjectID format

For example, if your userId is 5f6cb0496a8c5a0deaa1a746, it will be converted to

ObjectId("5f6cb0496a8c5a0deaa1a746")

When using strings instead of ObjectId, it may not work properly. You can see an example here: https://mongoplayground.net/p/5PN8WeXt2zc

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

React using Firebase: Receiving error "Cannot use import statement outside a module"

I've been following a helpful tutorial on setting up firebase authentication with React. However, I encountered some issues while trying to configure Firebase. I have created a firebase.js file as per the tutorial instructions: import firebase from &q ...

Intercommunication of variables among components

My scenario involves two components, namely App and SomeComponent. I'm aiming to access a variable in App from SomeComponent. App: import React, { Component } from 'react'; import logo from './logo.svg'; import './App.css& ...

Comparing npm install --save versus npm install --save-dev

Hey everyone, I've been using npm install -g to globally install node modules/packages, but I'm a bit confused about the --save and --save-dev options. I tried looking it up on Google, but I'm still not entirely sure. Can you guys help clar ...

Having trouble pinpointing the issue with my JavaScript code

Recently, I've been experimenting with JavaScript code snippets and after making some edits to one particular sample, I can't seem to figure out why it's not working. Everything appears correct to me, but here is the code snippet (JSFiddle) ...

Traverse through an array of objects with unspecified length and undefined key names

Consider the following object arrays: 1. [{id:'1', code:'somecode', desc:'this is the description'}, {...}, {...}] 2. [{fname:'name', lname:'last name', address:'my address', email:'<a h ...

Does the String.replace() function in Javascript have the capability of incorporating line breaks?

Is it possible to use the String.replace() method in JavaScript to replace any character with a line feed symbol? For example: newString = oldString.replace(/x/, "linefeed character (\n)"). ...

Need to update React textarea with value that is currently set as readonly

In my React application, I have a textarea that is populated with a specific value. My goal is to allow this textarea to be updated and then submit the form in order to update the corresponding row in the database. <textarea id="description" className= ...

Comparing Optimistic Updates and Tag Invalidation in RTK Query

I found a basic code example from the RTK query documentation: updatePost: build.mutation<void, Pick<Post, 'id'> & Partial<Post>>({ query: ({ id, ...patch }) => ({ url: `posts/${id}`, method: 'PUT', ...

When trying to use setInterval () after using clearInterval () within an onclick event, the functionality seems

Can anyone assist me with an issue I am encountering while using the setInterval() function and then trying to clear it with clearInterval()? The clearInterval() works fine, but the automatic functionality of li elements with a specific class suddenly stop ...

Can you determine if the user is holding the CTRL key in a universally recognized way?

Can JQuery or Javascript detect if the user is holding the CTRL key outside of keyPress, keyUp events? Appreciate any insights. Thanks! ...

What is the behavior of the JavaScript event loop when a Promise's resolution is tied to setTimeout?

console.log('1') setTimeout(() => { console.log('2') }, 0) function three() { return new Promise(resolve => { setTimeout(() => { return new Promise(resolve => resolve('3')) },0) ...

What is the best approach for retrieving specific data from MongoDB in a Node.js application using the GET method?

I have a variety of collections stored on a remote MongoDB server. My objective is to retrieve a specific collection based on the city name. I am currently using POSTMAN to mimic a GET request, but it seems that a different GET method is being triggered: { ...

"Combining multiple DIVs into a single DIV with jQuery - a step-by-step guide

I have multiple DIVs with the same class, and I am looking to group them into a single DIV using either jQuery or pure JS. <div class="a"> <div>1</div> </div> <div class="a"> <div>2</div> ...

Mongoose - Navigating Across Levels

I'm just starting to learn about MongoDB and Mongoose Here is the data I have: { "_id": "5787009e494495e56d327417", "title": "Hahaha", "parent": null, "depth": 0 }, { "_id": "5787009e494495e56d327416", "title": "Hihihi", "parent": null ...

Tips for updating the filename in a file input using AngularJS

Is it possible to dynamically change the name of a chosen file? For instance, if I select a file with the name "img1", can it be automatically changed to a different dynamic name upon selection? <input type="file" fd-input/> https://i.sstatic.net/d ...

The error message "angularjs is unable to assign a value to the property 'students' as it is

After setting ClassesServices to the classes array, I tried adding students of the class to a new property called classes.students. However, I encountered an error message saying 'Cannot set property 'students' of undefined.' $scope.cl ...

Developing a vue.js component library without the need for constant rebuilding after every edit

Introduction: I have created two projects using vue-cli ~4.2.0: parent-app - the main project dummylib - a library that is imported by parent-app. It contains several .vue components. Currently, parent-app functions well in dev mode with dummylib being ...

handling component interaction with react-redux store

Currently, I am in the process of developing my first significant project using react-redux. While trying to establish state mapping between components in react-redux, I seem to have missed a crucial step. Almost everything is functioning smoothly except ...

Calculate the sum of the elements within an array that possess a distinct attribute

I need to calculate the sum of certain elements in an array. For example, let's consider this array: var sampleArray = [ {"id": 1, "value": 50, "active": true}, {"id": 2, "value": 70, "active": false}, ...

Organize according to the registered membership status

I am dealing with Scorecards that represent user scores for matches. My goal is to sort these scorecards based on the date of each match, which is stored in a separate property. However, both the Scorecard and the Match are individual documents, not embe ...