I'm currently working on developing an application using Express and Firebase Cloud Functions. I'm facing a challenge in creating a nested JSON structure based on the database schema specified below:
https://i.sstatic.net/2vI8z.png
Below is the code snippet that I am using:
exports.tstMenu = (req, res) => {
let shop = db.collection('shops').doc(req.params.name).collection('menus');
shop.get()
.then((data) => {
let menu = [];
data.forEach((doc) => {
let categories = getCategories(doc.id, shop);
menu.push({
menuID: doc.id,
name: doc.data().name,
position: doc.data().position,
categories: categories,
});
console.log(menu);
});
return res.json(menu);
})
.catch((err) => {
console.error(err);
return res.status(500).json({ error: err.message});
});
}
function getCategories(id, db){
let shop = db.doc(id).collection('categories');
return shop.get()
.then((data) => {
let categs = [];
data.forEach((doc) => {
var menuElements = [];//getMenuElement(doc.id, shop);
categs.push({
catID: doc.id,
name: doc.data().name,
position: doc.data().position,
menuElements: menuElements,
});
});
return categs;
});
}
The output of tstMenu
is as follows:
https://i.sstatic.net/z08yf.png
However, the log displays this:
https://i.sstatic.net/pZLjA.png
I'd appreciate any assistance in understanding how to address this issue. It seems like the promises are not being resolved when tstMenu
reaches return res.json(menu);