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

106
Visualizações
How to nest separate documents by parent id in express.js?

I am warking in a ecomerce website. I have create a mongoose model for all categories. But including parent id for the category that is a subcategory. when get a request all the catagory is finding from databess. Thats fine but I want to send the catagory in a nested way. That's why I write like this.

//   This is router

Router.get('/categories', async (req, res) => {


    const createCategory = (categories, parentId = null) => {

        const categoryList = []
        let category

        if (parentId === null) {
            category = categories.filter(cat => cat.parentId === undefined);
        } else {
            category = categories.filter(cat => cat.parentId === parentId)
        }

        for (let cate of category) {
            categoryList.push({
                _id: cate._id,
                name: cate.name,
                slug: cate.slug,
                children: createCategory(categories, cate._id)
            })
        }


        return categoryList
    }

    try {

        const categories = await Category.find({})

        const categoryList = createCategory(categories)

        res.status(200).json({ categoryList })

    } catch (error) {

        res.status(500).json("server side error")
    }
})



// This is mongoose model 


const mongoose = require('mongoose');

const categorySchema = new mongoose.Schema({
    name: {
        type: String,
        required: true,
        trim: true,
        unique: true
    },
    slug: {
        type: String,
        required: true,
        unique: true
    },
    parentId: {
        type: mongoose.Schema.Types.ObjectId
    }

}, { timestamps: true })

module.exports = mongoose.model("Category", categorySchema)

Them problem is when I tring to get data from clint only root level catagory is outputing which has no parent id. but children array is empty like this.

{
    "categoryList": [
        {
            "_id": "613af0410977fb9fefd2e605",
            "name": "Electronics",
            "slug": "Electronics",
            "children": []
        }
    ]
}

I think the "createCategory" recuresive function is not working.

please anyone help me I am new in this fild...

about 4 years ago · Juan Pablo Isaza
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