I am trying to fetch data from two different collection category_types
and categories
. Each category has a parent category_type. So i want to push the category_type details when finding all the categories, in every index of category.
Here is my code
exports.findAllWithParentChild = (req, res) => {
let resData = [];
Models.Category.find()
.then(data => {
data.forEach(element => {
Models.CategoryType.findById(mongoose.Types.ObjectId(element.categorytype_id))
.then(catType => {
resData.push(element, {'category_type' : catType})
})
});
console.log(resData)
res.send({
response: true,
message: 'Categories fetched successfully.',
data : resData
});
}).catch(err => {
res.status(500).send({
response: false,
message: "Some error occurred while retrieving."
});
});
};
If i console resData
within the loop then it prints data correctly, outside of loop it is empty and also send empty response.
I want the format should look like this
[{
_id: 5cb2f300ce34a53c9070ca9c,
title: 'edeededede',
description: 'dededededed',
slug: 'ededede',
categorytype_id: 5cb2f247db13d03360a3a3c5,
user_id: 'dedede',
created_at: 2019-04-14T08:44:48.516Z,
updated_at: 2019-04-14T08:44:48.516Z,
__v: 0 ,
category_type:
{
_id: 5cb2f247db13d03360a3a3c5,
title: 'trgtrgtrg',
description: 'trgtrgtrg',
slug: 'trgtrgtr',
user_id: 'gtrgtrgtr',
created_at: 2019-04-14T08:41:43.935Z,
updated_at: 2019-04-14T08:41:43.935Z,
__v: 0
}
}]
If there is any better way let me know.