Home > other >  Response returned as null for Nested mongodb queries from Node JS React
Response returned as null for Nested mongodb queries from Node JS React

Time:11-02

I have a an api call handler coded out like this in Node JS Express.

const express = require("express");
const router = express.Router();
const PostModel = require("../models/postModel");
const ProfileModel = require("../models/profileModel");
const multer = require("multer");
const fs = require("fs");
const path = require("path");
const uuid = require("uuid");
//please ignore unused dependencies because im using them in other api call handlers
router.post('/get-posts/', (req, res) => {
    const { userId } = req.body;

    PostModel.find((err, postData) => {
        if(err){
            return res.send({
                success: "False",
                message: "Error while getting posts"
            });
        }

        const data = [];
        postData.forEach(async (p, index) => {
            const b64 = Buffer.from(p.post.image.data).toString('base64');
            const mimeType = p.post.image.contentType;
            const url = `data:${mimeType};base64,${b64}`;

            var ddd = await ProfileModel.findOne({
                userId: p.authorId
            }, async (e, d) => {
                if(e){
                    console.log(e);
                }
                
            }).clone();

            let dpMimeType = ddd.profilePic.contentType;
            let dpUrl = `data:${dpMimeType};base64,${b64}`;

            const obj = {
                authorId: p.authorId,
                postId: p.postId,
                dp: dpUrl,
                post: {
                    authorName: p.post.authorName,
                    creationDate: p.post.creationDate,
                    heading: p.post.heading,
                    image: url,
                    message: p.post.message,
                    likes: p.post.likes,
                    dislikes: p.post.dislikes,
                    hearts: p.post.hearts,
                    comments: p.post.comments,
                    likedUsers: p.post.likedUsers,
                    dislikedUsers: p.post.dislikedUsers,
                    heartedUsers: p.post.heartedUsers
                }
            };
    
            data.push(obj);
        });

        if(postData.length > 0){
            return res.status(200).send({
               posts: data 
            });
        } else {
            return res.status(200).send({
                message: "No posts found for this user"
            });
        }
    });
});

Now what Im doing here is Im fetching all posts from the PostModel from the db. Then I iterate over each of those posts, then query that post's authorId and pass it to the ProfileModel to get back the author's dp, attach it to my response body and send it back to my React frontend frm where I can access the same and display the author's dp along with the author's post.

But the problem that occurs here is that, Im getting the following response from the api call:-

{"posts":[]}

that is, a blank response is returned. But there is no errors logged out anywhere neither does my node server break due to some errors. It runs smoothly, but there is no response returned inspite of the fact that there are enough documents in both the collections in the db. So its not a problem of the db being empty.

I have no idea what to do. Any and all help is massively appreciated.

CodePudding user response:

forEach is not meant to be used with async await, try with this logic:

router.post('/get-posts/', async (req, res) => {
  try {
    const { userId } = req.body;

    const postData = await PostModel.find({});
    if (postData.length === 0) {
      return res.status(400).send({
        message: 'No posts found for this user',
      });
    }

    const data = [];
    for (const p of postData) {
      const b64 = Buffer.from(p.post.image.data).toString('base64');
      const mimeType = p.post.image.contentType;
      const url = `data:${mimeType};base64,${b64}`;

      var ddd = await ProfileModel.findOne({
        userId: p.authorId,
      });

      let dpMimeType = ddd.profilePic.contentType;
      let dpUrl = `data:${dpMimeType};base64,${b64}`;

      const obj = {
        authorId: p.authorId,
        postId: p.postId,
        dp: dpUrl,
        post: {
          authorName: p.post.authorName,
          creationDate: p.post.creationDate,
          heading: p.post.heading,
          image: url,
          message: p.post.message,
          likes: p.post.likes,
          dislikes: p.post.dislikes,
          hearts: p.post.hearts,
          comments: p.post.comments,
          likedUsers: p.post.likedUsers,
          dislikedUsers: p.post.dislikedUsers,
          heartedUsers: p.post.heartedUsers,
        },
      };

      data.push(obj);
    }

    return res.status(200).send({
      posts: data,
    });
  } catch (err) {
    res.status(500).send({
      success: 'False',
      message: 'Error while getting posts',
    });
  }
});
  • Related