I'm struggling with promises with Mongoose because I am used to do synchronous programming.
Context
I have many categories. Each category have no or one parent category. A knowledge is associated with a category. I would like to create a tree with all categories with their sub-categories and knowledge(s).
Actually, it looks like a model with directories and files. The expected output would be like a JSON :
[
{"name": "cat0",
"children": [{"name": know0}]
},
{"name": "cat1",
...
]
Code
I use a recursive way. I call the function with null (which get all roots categories), then the recursive call will apply on the sub-categories.
static findKnowledgeByCategory(query = null){
return new Promise((resolve, reject) => {
CategoryModel.find({parent: query})
.then((categories) => {
console.log(query + ' : CategoryModel.find success');
return new Promise((resolve, reject) => {
console.log(query + ' : new Promise');
categories.forEach(cat => { // cat == { _id: ..., parent: ..., name: 'smthng' }
KnowledgeModel.find({category: cat._id})
.then((knowledges) => {
console.log(query + ' : KnowledgeModel.find success');
cat.knowledges = knowledges;
Model.findKnowledgeByCategory(cat._id)
.then((categories) =>{
cat.children = categories;
});
})
})
}).then(() => {
console.log(query + ' : Début resolve');
return resolve(categories);
})
})
.catch((err) =>{
console.log(err);
return reject();
} )
});
}
I must return a promise with this code, because at a more global scope its resolve is used to return the tree in JSON.
Global Scope
findKnowledgeByCategory()
.then((catAndKnow) => res.status(200).json(catAndKnow))
.catch(err => Validation.handleError(res, 500, err));
There is no error displayed, but when I call the function, the server does not respond.
Notice it will never display "Début resolve"... I'm using Node 6.11.2 so I can't use "await". Any idea would be appreciated. I apologize if my issue is not relevant. I think I don't manage well my promises but I don't have any clue.