0

I believe it may just be an error in my logic, but i'm not sure where the problem is exactly and I am looking for help debugging. I am using Firebase Cloud Firestore. I am trying to query through my "follows" collection to return all data where the key "senderHandle" is equal to the params handle and then push that data to the empty array followData. Then, loop through each followData and make a document query call to the "posts" collection. Then, loop through each of the returned documents from the "posts" collection and push each data to the empty array "posts".

When I try to return the posts array though it returns empty. My overall goal is to get all of the users the params handle follows, loop through each user to get their posts, and then push their posts into an empty array.

Functions code:

// fetch home-specific posts (of users following)
exports.getHomePosts = (req, res) => {
  let posts = [];
  let followData = [];
  // get following users
  const followDocument = db
    .collection("follows")
    .where("senderHandle", "==", req.params.handle);

  followDocument
    .get()
    .then((data) => {
      if (data.query.size == 0) {
        return res.status(400).json({ error: "Not following any users" });
      } else {
        data.forEach((doc) => {
          followData.push(doc.data());
        });
      }
    })
    .then(() => {
      followData.forEach((follow) => {
        db.collection("posts")
          .where("userHandle", "==", follow.receiverHandle)
          .where("location", "==", "explore")
          .get()
          .then((data) => {
            data.forEach((doc) => {
              posts.push({
                postId: doc.id,
                body: doc.data().body,
                userHandle: doc.data().userHandle,
                createdAt: doc.data().createdAt,
                commentCount: doc.data().commentCount,
                likeCount: doc.data().likeCount,
                userImage: doc.data().userImage,
              });
            });
          });
      });
      return res.json(posts);
    })
    .catch((err) => {
      res.status(500).json({ error: err.message });
    });
};

followData returned:

[
    {
        "receiverHandle": "John Doe",
        "senderHandle": "bear"
    },
    {
        "senderHandle": "bear",
        "receiverHandle": "Yikies"
    },
    {
        "receiverHandle": "bear",
        "senderHandle": "bear"
    },
    {
        "receiverHandle": "anon",
        "senderHandle": "bear"
    },
    {
        "senderHandle": "bear",
        "receiverHandle": "BigYikes"
    }
]

1 Answer 1

1

There are multiple issues with this code.

  1. You are not waiting promise to be resolved.
  2. Multiple returns statements
  3. You would not create global arrays like posts and followData[you can return in then for next callback]

Code:

// fetch home-specific posts (of users following)

exports.getHomePosts = (req, res) => {
  const followDocument = db
    .collection("follows")
    .where("senderHandle", "==", req.params.handle);

  followDocument
    .get()
    .then((data) => {
      if (data.query.size == 0) {
        throw new Error("NOT_FOUND");
      } else {
        return data.map((doc) => doc.data());
      }
    })
    .then((followData) => {
      const promises = followData.map((follow) => {
        return db
          .collection("posts")
          .where("userHandle", "==", follow.receiverHandle)
          .where("location", "==", "explore")
          .get();
      });
      Promise.all(promises).then((results) => {
        const posts = results
          .map((data) => {
            return data.map((doc) => ({
              postId: doc.id,
              body: doc.data().body,
              userHandle: doc.data().userHandle,
              createdAt: doc.data().createdAt,
              commentCount: doc.data().commentCount,
              likeCount: doc.data().likeCount,
              userImage: doc.data().userImage,
            }));
          })
          .flat();
        return res.json(posts);
      });
    })
    .catch((err) => {
      if (err.message === "NOT_FOUND") {
        return res.status(400).json({ error: "Not following any users" });
      }
      res.status(500).json({ error: err.message });
    });
};
Sign up to request clarification or add additional context in comments.

3 Comments

Hi, thank you for your quick reply! I am getting error that data.map is not a function, which I assume is because data is an object not an array. Would my alternative solution be Objects.keys?
yeah!.. i m not sure ur result. please try console log and check.. i just highlighted mistakes that u can correct and a rough sample.
Thank you very much! I will mess with the code some more, I appreciate your guidance!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.