How come I am not finding any results when trying to search for a specific subdocument within a document? (mongodb and mongoose)

I'm having trouble fetching all documents that contain the user in their array of member subdocuments. I've tried using the aggregate framework, but it always returns 0 results.

Interestingly, when I use the .find() method, it works perfectly fine. However, the query doesn't seem to work with aggregate.

await this.groupModel
  .find({ 'members.user_id': userId })
  .limit(limit)
  .sort({ updatedAt: 'desc' })
  .lean()

Here's an example document:

{
  "_id": {
    "$oid": "614e0ab5a828578b4b2ee137"
  },
  "last_message": null,
  "nsfw": false,
  "icon": null,
  "description": "test.",
  "name": "test",
  "owner": {
    "$oid": "613fbe66c4c1631c28ccfd5a"
  },
  "roles": [],
  "members": [
    {
      "roles": [],
      "avatar": "a",
      "nickname": null,
      "user_id": {
        "$oid": "613fbe66c4c1631c28ccfd5a"
      },
      "_id": {
        "$oid": "614e0ab5a828578b4b2ee139"
      },
      "updatedAt": {
        "$date": "2021-09-24T17:28:21.524Z"
      },
      "createdAt": {
        "$date": "2021-09-24T17:28:21.524Z"
      }
    }
  ],
  "createdAt": {
    "$date": "2021-09-24T17:28:21.500Z"
  },
  "updatedAt": {
    "$date": "2021-09-24T17:28:21.524Z"
  },
  "__v": 0
}

This is the query I'm running:

await this.groupModel
  .aggregate<GroupDocument>()
  .match({
     'members.user_id': userId
  })
  .addFields({
  members_count: { $size: '$members' },
})
// ===> Result: []

Variables being used:

userId: string

Answer №1

The issue lies in the fact that the query is matching both a string and an ObjectId.

To solve this, you can convert your string to an ObjectId by using mongoose.Types.OjectId(userId) like so:

await this.groupModel
  .aggregate<GroupDocument>()
  .match({
     'members.user_id': mongoose.Types.OjectId(userId)
  })
  .addFields({
    members_count: { $size: '$members' },
})

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

MongoDB intricate shape with inner void

Is there a method to query a complex polygon with a hole? Take for example: [ [ // hole rectangle [ 59.187, 42.891 ], [ 59.187, 13.997 ], [ 46.377, 13.997 ], [ 46.377, 42.891 ] ], [ // border rectangle [ 63.802, 57.964 ], ...

What is the best approach to processing data from a form containing multiple fields in a Node.js application?

I am currently designing a webpage dedicated to RSVPs for a wedding website. The process involves the guest inputting their email address, and then the page will search for all guests listed on that specific invitation before generating a table: <%- inc ...

Lazy loading in Angular 2 hits a snag when using a module that is shared

After successfully lazy loading my AccountModule, I encountered an issue when adding my SharedModule to it. All of my eagerly loaded modules seemed to be forgotten and I started receiving the following error: The component FoodComponent is not part of a ...

What could be causing routerLink to malfunction despite correct configuration?

Is routerLink properly placed in the view? <p><a routerLink="/registration" class="nav-link">Register</a></p> Checking my app.module import { NgModule } from '@angular/core'; import { BrowserModule } from '@angular ...

Revolutionizing SEO with MEAN.js dynamic metadata

After using the command yo meanjs:crud-module modulename to generate a meanjs crud module, I am facing a challenge with changing the meta data values for view.modulename.client.html. These values are generated on the server side in layout.server.view.html ...

Storing Objects in MongoDB using Node.js

I am working on an application where I need to store an object for later execution of functions. This object essentially holds the data of a cron job. var cronJobObject = schedule.scheduleJob(new Date(2018, 0, 19, 15, 15, 0), function() { console.log( ...

Storing JSON strings in MongoDB using Java

Various tutorials, such as this one and this one, explain how to save JSON data using the JSON.parse method which returns DBObject. While this method is simple and concise, I can't help but wonder why we need to parse the JSON in the first place. Can& ...

Storing the author's unique identification in the database - how can we retrieve the author's name when transmitting information to

Is there a way to convert userIDs to usernames of users when transferring data from the database? I have thought about using middlewares, but I am not sure how to execute it. Here is my route: router.get('/recentQuizzes', async (req, res) => { ...

How can I place a definition file so that it can be easily accessed across multiple applications within NRWL?

I've been utilizing NRWL to organize my projects. Currently, I'm working on two projects that require custom definition files for TypeScript - namely json-typings.d.ts and custom.d.ts. For example, here's the content of the json-typings.d.t ...

PreventDefault was ineffective in handling close/minimize/maximize BrowserWindow events in electron

I need help with customizing the behavior of the close, minimize and maximize events in the Electron browser window. I have been able to capture these events, but using event.preventDefault() does not seem to work as expected. Rather than disabling the win ...

What could be causing a Typescript-defined class property to unexpectedly appear as undefined?

My component has a property called options, which I have defined in the class. However, when I run the code in the browser, it's showing up as undefined. Despite thoroughly checking the code logic, I can't seem to pinpoint any issues. This could ...

The Subscribe function in Angular's Auth Guard allows for dynamic authorization

Is there a way to check if a user has access by making an API call within an authentication guard in Angular? I'm not sure how to handle the asynchronous nature of the call and return a value based on its result. The goal is to retrieve the user ID, ...

Adding a type declaration to the severity property in React Alert - A guide to Typescript

I've developed a type declaration object for the incoming data, but no matter what I try to define as the type for the property "severity", it's not happy. The options it wants (as displayed below) don't seem feasible. I'm curious if th ...

Mongoose managing diverse connections

Currently, I am working with Node.Js 8.6 and Mongoose 4.11, managing multiple database connections using mongoose.createConnection. Upon exploring the connections property within the mongoose object (an array that stores established connections), I am curi ...

Changing Databases in a NextJS Application using Mongoose

Recently, I've been exploring the idea of integrating database switching into a NextJS application. While I am somewhat new to NextJS as a framework, I do have previous experience working with NodeJS and React. In a Node environment, this concept migh ...

What is the proper way to utilize this xd-file package?

I'm currently working on manipulating an Adobe XD file using a specific package. If you're interested, here's the link to the package: xd-file My goal is to incorporate this code snippet into a JavaScript file, utilizing Node.js. The meth ...

The provider for the NoSQL Datastore is org.hibernate.ogm.datastore.mongodb.impl.MongoDBDatastoreProvider

My current challenge involves connecting to a MongoDB through the provided persistence.xml file. In this case, my mongodb instance does not require any username or password for authentication. <?xml version="1.0" encoding="UTF-8"?> <persi ...

Preventing JavaScript Compilation for a Specific Folder using tsconfig: A Step-by-Step Guide

To create my own npx package, I'm currently working on converting my .ts files into .js. The purpose of the application is to generate TypeScript templates for users based on their selected options. In this app, there's a CLI called 'index.t ...

Adding precise data values of an item into mongodb utilizing nodejs

Using nodejs for server side connection, I have a json object which needs to be inserted into MongoDB based on certain conditions. The JSON data is as follows: "_id" : ObjectId("5a1507f7c6e9dc046ee76b01"), "sendStatus" : false, "draftName" : "ife ...

Determining the appropriate time to use either `mongoose.disconnect()` or `db.close()` can depend

Having recently started using MongoDB and Mongoose in my express.js application, I am unsure about when to close the connection. Some recommend closing it, while others suggest leaving it open. What is your opinion on this? Additionally, could you explain ...