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...