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

136
Visualizações
MongoDB - Remove object from SubArray

I'm trying to remove an object from a subarray with no luck getting updateOne() is not a function and remove() is not function.

I want to remove the 'subcat 1' object with id of '61cae5daf5bfbebd7cf748ef':

[
 {
     _id: '61cae5daf5bfbebd7cf748ee'
     title: 'category 1',
     SubCats: [
         {
             _id: '61cae5daf5bfbebd7cf748ef'
             name: 'subcat 1',
             image: '/assets/images/vr-box-6203301_1920.jpg',
         },
         {
             _id: '61cae5daf5bfbebd7cf748fb'
             name: 'subcat 2',
             image: '/assets/images/galaxy-s20_highlights_kv_00.jpg',
         },
     ]
 },
]

Please help

Controller:

const deleteSubCategory = asyncHandler(async (req, res) => {
 const subCategory = await Category.aggregate([
     { $unwind: "$SubCats" }, 
     { $replaceRoot: { newRoot: '$SubCats'} }, 
     { $match: { _id: ObjectId(req.params.id) }}
 ])

 if (subCategory) {
     await subCategory.updateOne({ $pull: {_id: ObjectId(req.params.id)}})
    res.json({ message: 'sub-category removed' })
 } else {
     res.status(404)
     throw new Error('sub-Category not found')
 }
})
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

$update with $pull

db.collection.update({
  "SubCats._id": "61cae5daf5bfbebd7cf748ef"
},
{
  "$pull": {
    SubCats: {
      _id: "61cae5daf5bfbebd7cf748ef"
    }
  }
},
{
  "multi": true
})

mongoplayground

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