我在试着让所有的消息都在聊天中。每个文档都有一个"messages“数组,它映射到消息体、createdAt和发送者的用户名。chat中的所有用户都有第二个数组。

如何返回消息数组的最后10个元素?
代码:
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 });
});
};到目前为止,我的代码返回一个空的消息数组。
发布于 2020-08-09 09:34:52
当查询Firestore时,不可能指示查询从数组字段中过滤出项目。您必须读取整个数组字段,然后决定如何处理该数组中的项。因此,这意味着第二个查询在这里没有帮助。在第一个文档快照中,您已经拥有了所需的所有内容。
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
})https://stackoverflow.com/questions/63321574
复制相似问题