I have a sequelize model, comment which has a belongsTo relationship with itself, used to denote the parent comment, if there is one, such as this:
models.comment.belongsTo(models.comment, {
as: 'parent',
foreignKey: 'parentId'
});
I am trying to get all the comments that belong to a specific article ID by a simple RESTful API:
router.get('/article/:id/comments', (req, res, next) => {
models.comment.findAll({
where: {
articleId: req.params.id,
parentId: null
}
}).then(roots => {
// iterate thru each root asynchronously and get its children
async.each(roots, (root, callback) => {
root.getChildren().then(children => {
// set the object's children to this result
root.children = children;
callback();
});
}, (err) => {
if(!err) {
return res.status(200).json(roots);
}else {
return res.status(400).json({error: err});
}
});
}).catch(err => {
return res.status(400).json({error: err});
});
});
The getChildren() instance method in Sequelize returns the immediate children of any comment, by virtue of finding any other comments whose parent is that comment (i.e., a reply). It works with the first layer of replies, such as this:
- Parent 1
- Child 1
- Child 2
- Child 3 << This one isn't included
- Child 4 << Obviously, this one neither
- Parent 2
- Child 5
- Child 6
But if I add any more depth, it won't. The method is as follows:
comment.prototype.getChildren = async function() {
let results = [];
await comment.findAll({ where: { parentId: this.id }}).then(children => {
results = children;
// recursive logic here
// ?????
});
return results;
}
How can I implement the recursive logic so that getChildren() calls itself to get N-layers of depth in the nested comments and return a fully structured JSON data tree to be used in a front-end? I haven't studied recursion very well and I am having problems wrapping my head around it when you have to do everything asynchronously in nodejs.
I'm not looking for a MySQL solution.
Thank you.