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.
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.
