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

114
Vistas
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 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