Retrieving a specific object from a subarray using MongoDB's ID

My MongoDB document includes the following:

const Categories = [
{
    _id: 's654fs54s6d4f'
    title: 'category 1',
    SubCats: [
        {
            _id: 'jhgfsf68746'
            name: 'subcat 1',
            image: '/assets/images/vr-box-6203301_1920.jpg',
        },
        {
            _id: 'vb40n5b4vn'
            name: 'subcat 2',
            image: '/assets/images/galaxy-s20_highlights_kv_00.jpg',
        },
    ]
},
]

This is the schema related to the document:

import mongoose from 'mongoose'

const Catschema = mongoose.Schema({
    name: {
        type: String,
        required: true,
    },
    image: {
        type: String,
        required: true,
    },
})

const CategorySchema = mongoose.Schema(
    {
        title: {
            type: String,
            required: true,
        },
        SubCats: [Catschema]
    },
    {
        timestamps: true,
    }
)

const Category = mongoose.model('Category', CategorySchema)

export default Category

To retrieve 'category 1' by its id, I use the following code:

const getCategoryById = asyncHandler(async (req, res) => {
  const category = await Category.findById(req.params.id)
})

The output will be the entire array.

Now, my query is about how to fetch the object 'subcat 1' using its id 'jhgfsf68746'.

Here's the desired output format:

{
  _id: 'jhgfsf68746'
  name: 'subcat 1',
  image: '/assets/images/vr-box-6203301_1920.jpg',
}

Answer №1

Unsure which field serves as the default key in mongodb in this instance, however, a solution is provided below. It's crucial to determine whether _id or id is the correct one for your situation. Additionally, the strings have been hardcoded.

User.findOne({_id: 's654fs54s6d4f'})
  .select({ 
    SubCats: {
      $elemMatch: {_id: 'jhgfsf68746'}
    }
  })

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

How can you showcase the content of an object within an array?

I am currently working on a project component that involves retrieving and logging data. However, I am facing an issue with accessing objects within my array of clients to display them properly in my table. Here is the script I am using: <script> ex ...

I am experiencing unexpected results with my Mongoose filter and sort query in Express JS middleware. The output does not match what I am anticipating, and the sorting functionality seems to

This middleware is used for filtering and sorting data. I made some modifications to it, but it's not functioning as expected: const aliasTopMenu = (req, res, next) => { req.query.sort = '-price'; req.query.fields = 'name,price, ...

When should separate controllers be created for a list of values in a Laravel REST API?

Imagine I have a straightforward API for user registration. This API collects basic information like Name, email, state, gender, and marital status for each user. I already have database tables pre-populated with ids for state, gender, and marital status o ...

Sending a POST/PUT request from AngularJS to Java triggers an error message: 'Access control check failed for preflight request'

After doing some research on the issue, I've discovered that it is related to CORS. Unfortunately, I'm unsure of the best way to resolve it. I have a Java web service up and running which includes various GET/POST/PUT/DELETE resources. It's ...

Turning off the MaskedEditValidator and MaskedEditExtender

I have created a compact table that allows users to edit, delete, and add records: The table (DataGridView, bound) is user-friendly: click on "Edit" to enter the editing mode (which includes a "Cancel" option), update values, and then click "Add" to inser ...

Is it possible to use Express.js in conjunction with Node.js net to set up a TCP protocol listener?

Currently in the process of developing a chat server with expressjs. I was wondering if it is feasible to utilize both expressjs and the nodejs net module for the application in order to have it listen on tcp port 7677 for incoming messages. Appreciate a ...

Having difficulty adding items to the shopping cart

While working on a simple checkout system using django and react, I encountered an issue. Upon clicking the add to cart button, instead of adding the item to the cart as intended, I receive a 404 page not found error. I suspect that the problem may lie in ...

Encountered an error trying to access property 'history' of an undefined value while using react-router v4 and create-react-app

I encountered an issue with using Link to navigate, here's the breakdown of my code: Directory structure components ----App.js ----home ----Home index.js index.js import React from 'react'; import ReactDOM from 'react-dom'; ...

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 ...

Using React to Filter cards according to the selected value from an Autocomplete feature

I'm currently developing a React application that utilizes Material-UI's Autocomplete component to filter cards based on selected car brands. These cards represent various models, and the goal is to update them when a user picks a brand from the ...

Opt for CSS (or JavaScript) over SMIL for better styling and animation control

I recently noticed an alert in my Chrome console that SVG's SMIL animations are being deprecated and will soon be removed. The message suggested using CSS or Web animations instead. Since I want to transition from SMIL to CSS animations, there are a ...

Silhouettes dancing across handcrafted designs

I have been trying to create a custom geometry using vertices and faces, but I am facing an issue where the geometry does not cast shadows on itself and the faces all have the same color as it rotates. I have attempted various solutions but haven't ha ...

When attempting to retrieve the innerHTML of a <div> element within a <Script> tag, the value returned is undefined

Utilizing a masterpage to create a consistent header across all content pages, I encountered an issue on one page. I needed to retrieve the innerHTML of a div element and pass it to an input control on the same page in order to access the updated innerHTML ...

Using Angular and Jasmine: techniques for simulating a service that provides a promise

In my AngularJS application, I have a controller called MenuCtrl that utilizes a service provided by "$mdSidenav" from Angular Material. This service is created using a factory method. angular.module('leopDirective', []) .controller('Me ...

Listening for changes in class property values in TypeScript with Angular involves using the `ngOnChanges`

Back in the days of AngularJS, we could easily listen for variable changes using $watch, $digest... but with the newer versions like Angular 5 and 6, this feature is no longer available. In the current version of Angular, handling variable changes has bec ...

What is causing setTimeout to not function as intended?

I'm having some trouble moving a <div id="box"> whenever my mouse hovers over it. Currently, the element only moves when I trigger the mouseover event on the div itself instead of when my mouse is actually hovering over it. document.getElements ...

Activate the text area message by clicking on the href link

I am currently working on customizing the intercom plugin for a WordPress site. My goal is to have a message triggered when a user clicks on a hyperlink, essentially simulating the enter key press in a textarea. Here is the code snippet that I am using: ...

Generating several files from one through aggregation

I have a data collection containing documents like the following: { "_id" : ObjectId("5f797a8f03b66b73edd4f56f"), "totalCounts" : 2300, "roadId" : "road_2", "type" : "CALL ...

Having trouble with my React Next app, it's giving me an error stating "window is not defined

Currently, I am developing in Next.js using React components and encountering an issue. I keep receiving a ReferenceError: window is not defined error in react-location-picker. If you need to check out the package, here is the link: react-location-picker ...

Ways to manage an element that has been loaded using the load query function

After implementing the query load function to update posts on the homepage, I was able to display the most up-to-date posts. However, a new issue arose: Whenever I updated all posts without refreshing the entire page, I needed a way to control the element ...