Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

110
Views
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
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!