Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

89
Views
mongoDB - get object from subArray by id

so i have the following document in mongoDB:

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',
        },
    ]
},
]

and this is the schema:

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

i can get 'category 1' by its id using:

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

and the whole array would be the output.

my question is how to get object 'subcat 1' by its id 'jhgfsf68746'.

Desired output:

{
  _id: 'jhgfsf68746'
  name: 'subcat 1',
  image: '/assets/images/vr-box-6203301_1920.jpg',
},
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

Im not sure which field is the default mongodb key in your example, but here is how you can solve it, just make sure which once is correct for you _id or id. Also, I've hardcoded the stings

User.findOne({_id: 's654fs54s6d4f'})
  .select({ 
    SubCats: {
      $elemMatch: {_id: 'jhgfsf68746'}
    }
  })
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!