Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

91
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda