Firebase Part IX: Adding and Viewing Comments

7th Oct 19

I am adding the ability for users to comment on topics posted.

I want registered users to be able to comment on topics:'/forum/:topicId/comment', FBAuth, commentOnTopic)

The commentOnTopic function required authentication and user data such as profile image and user id is extracted from the middleware function:

exports.commentOnTopic = (req, res) => {
    if(req.body.body.trim() == '') return res.status(400).json({error: 'Must not be empty'});

    const newComment = {
        body: req.body.body,
        createdAt: new Date().toISOString(),
        topicId: req.params.topicId,
        userHandle: req.user.handle,
        userImage: req.user.imageUrl

        .then(doc => {
            if(!doc.exists) return res.status(404).json({error: 'Topic not found'});
            return db.collection('comments').add(newComment)
        .then(() => {
            return res.json(newComment);
        .catch(err => {
            res.status(500).json({error: 'Something went wrong'});

The topic id is retrieved from the url.  Note that I had make some amends to FBAuth by extracting the user's imageUrl so that I could add the profile image to the comments.


Viewing Comments

For retrieving the comments I firstly extract the topic then from the topic data I retrieve the associated comments.  The topicId is extracted from the url.

exports.getTopic = (req, res) => {
    let topicData = {};
        .then(doc => {
                return res.status(404).json({error: 'Topic not found'})
            topicData =;
            topicData.topicId =;
            return db
                .orderBy('createdAt', 'desc')
                .where('topicId', '==', req.params.topicId)
        .then(data => {
            topicData.comments = [];
            data.forEach( doc => {
            return res.json(topicData)
        .catch(err =>{
            res.status(500).json({error: err.code});


I have recently completed my apprenticeship.  I am currently building the API to a React JS site using Firebase.