Why is the first response empty

Issue

I want to get all the comments of a post , i am using expressjs with mongodb, but i have a little issue , the first response is always empty here’s my code:

const Post = require("../models/posts"),
      Comment= require("../models/comments");
var commentsArray = [];

router.get("/post/:id/comments", async (req,res)=>{

        Post.findById(req.params.id).then( (post) => {
            post.comments.forEach(comment =>{
                if(commentsArray.length === 0  ){
                    Comment.findById(comment).then((comment)=>{
                        commentsArray.unshift(comment)
                    }); 
                 }
            });
        });
    
    return await res.json(commentsArray);
});

Solution

Well… Since Post.findById and Comment.findById are async functions the response is being returned before you fill your commentsArray. Additionally. using it as a global variable is bad practice because you will always return the previous results of other posts and duplicate the results on multiple calls on the same URI.

So… for resolving your issue await the Post.findById and Comment.findById before going forward. Additionally, for perfomance issues I recommend you review your need for using Comment.findById. There are ways where you could $lookup operator to do this in a single query.

const Post = require("../models/posts");
const User = require("../models/users");

router.get("/post/:id/comments", async (req,res)=> {
  if (! req.params.id) {
    // throw not found error
  }

  const post = await Post.findById(req.params.id);
  // is this really needed? is there anyway you can search for multiple items? if no...
  const comments = await Promise.all(
    post.comments.map(comment => Comment.findById(comment))
  );

  return res.json(comments);
});

Answered By – Rômulo Bourget Novas

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published