empty array when querying map of array in Firebase

Viewed 185

I'm trying to get all messages in a chat. Each doc has a "messages" array, which maps to message body, createdAt, and sender's username. There is a second array for all users in chat.

enter image description here

How do I return all of the last 10 elements of the messages array?

Code:

exports.getChat = (req, res) => {
  let chatData = {};
  db.doc(`/chats/${req.params.chatId}`)
    .get()
    .then((doc) => {
      if (!doc.exists) {
        return res.status(404).json({ error: "Chat not found." });
      }
      chatData = doc.data();
      chatData.chatId = doc.id;
      return db
        .collection("chats")
        .where("chatId", "==", req.params.chatId)
        .get();
    })
    .then((data) => {
      chatData.messages = [];
      data.forEach((doc) => {
        chatData.messages.push(doc.data());
      });
      return res.json(chatData);
    })
    .catch((err) => {
      console.error(err);
      res.status(500).json({ error: err.code });
    });
};

The code I have so far returns an empty messages array.

1 Answers

When querying Firestore, it's not possible to instruct the query to filter items out of an array field. You have to read the entire array field, then decide what you want to do with the items in that array. So, this means that a second query is not helpful here. You have everything you need in the first document snapshot.

  db.doc(`/chats/${req.params.chatId}`)
    .get()
    .then((doc) => {
      if (!doc.exists) {
        return res.status(404).json({ error: "Chat not found." });
      }
      const chatData = doc.data();
      // chatData now contains the entire contents of the document in the screenshot

      const messages = chatData.messages
      // messages now contains the entire array of messages - use however many want      
    })
Related