0

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.

  • Diego, I've written about anamorphisms a lot lately and `unfold` is exactly what you're looking for in this situation. Please read [this answer](https://stackoverflow.com/a/50121218/633183) and the Q&A's linked at the bottom of that post. The programs covered each deal with varying data structures, but the common parent->child relationship (of arbitrary depth) is a perfect use case. If you have trouble adapting the lessons to your code, send me a message and I'll help you out. – Mulan May 03 '18 at 02:46
  • meanwhile, can you update your answer to show the precise structure you wish the query to return? – Mulan May 03 '18 at 02:51

0 Answers0