so i have the following document in mongoDB:
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',
},
]
},
]
and this is the schema:
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
i can get 'category 1' by its id using:
const getCategoryById = asyncHandler(async (req, res) => {
const category = await Category.findById(req.params.id)
})
and the whole array would be the output.
my question is how to get object 'subcat 1' by its id 'jhgfsf68746'.
Desired output:
{
_id: 'jhgfsf68746'
name: 'subcat 1',
image: '/assets/images/vr-box-6203301_1920.jpg',
},
Im not sure which field is the default mongodb key in your example, but here is how you can solve it, just make sure which once is correct for you _id or id. Also, I've hardcoded the stings
User.findOne({_id: 's654fs54s6d4f'})
.select({
SubCats: {
$elemMatch: {_id: 'jhgfsf68746'}
}
})