Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

90
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda