im trying to create a seprate route in my api for a subArray from a nested array. using expressJs.
categories array:
const Categories = [
{
_id: 's654fs54s6d4f'
title: 'category 1',
SubCats: [
{
_id: 'jhgfsf68746'
name: 'subcat 1',
image: '/assets/images/vr-box-6203301_1920.jpg',
},
{
_id: 'vb40n5b4vn'
name: 'subcat 2',
image: '/assets/images/galaxy-s20_highlights_kv_00.jpg',
},
]
},
]
categoryModel:
import mongoose from 'mongoose'
const Catschema = mongoose.Schema({
name: {
type: String,
required: true,
},
image: {
type: String,
required: true,
},
})
const CategorySchema = mongoose.Schema(
{
title: {
type: String,
required: true,
},
SubCats: [Catschema]
},
{
timestamps: true,
}
)
const Category = mongoose.model('Category', CategorySchema)
export default Category
categoryController:
this would return the whole array
const getCategories = asyncHandler(async (req, res) => {
const categories = await Category.find({})
res.json(categories)
})
i want to return ‘SubCats’ array.
tried this but getting “SubCats is not defined”.
const getSubCategories = asyncHandler(async (req, res) => {
const subcategories = await Category.find({SubCats})
res.json(subcategories)
})