'Firebase (Node.JS) - data are not being added into the array
I've got one api functions, which is supposed to look for the categories, create an object, and add the object into the array. Meanwhile, during the looping through the categories, I would like to loop for every sub-category inside category and add for the previous object.
The function looks like:
exports.getAllCategories = (req, res) => {
db
.collection("categories")
.get()
.then((data) => {
let categories = [];
data.forEach((doc) => {
const categoryObj = {
id: doc.id,
name: doc.data().name,
subCategories: []
};
db.collection("subCategories").where("category", "==", doc.id).get()
.then((data) => {
data.forEach((doc) => {
let subCategoryObj = {
id: doc.id,
name: doc.data().name
}
categoryObj.subCategories.push(subCategoryObj);
})
console.log(categoryObj)
})
categories.push(categoryObj);
});
return res.json(categories)
})
.catch((err) => {
console.log(err);
})
}
console.log output:
> { id: 'nFj6UukoeEdUWfkOQlDO', name: 'properties', subCategories: [] }
> { id: 'uhD0nm6OgWqltviR21Iz', name: 'motorization', subCategories: [] }
> { id: 'myz2U3cguF8RaMiQSjM9', name: 'fashion', subCategories: [] }
> { id: 'wIxYC31aT4dBZ5DKVXpC', name: 'health', subCategories: [] }
> { id: 'Po0wuBA5DeIx9YzeFyKn', name: 'beauty', subCategories: [] }
> {
> id: 'LBMFjzmqW0EpNL2gKZdK',
> name: 'electronics ',
> subCategories: [
> { id: 'OeAcHaUs6KtqItk80V5J', name: 'RTV' },
> { id: 'QneYU1TfIvzTnn51sDLo', name: 'computers' }
> ]
> }
But when I call the API the electronics category has empty subCategories array.

Why?
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
