Javascript 在Firebase中查询数组映射时为空数组

Javascript 在Firebase中查询数组映射时为空数组,javascript,firebase,google-cloud-firestore,google-cloud-functions,Javascript,Firebase,Google Cloud Firestore,Google Cloud Functions,我正在尝试在聊天中获取所有消息。每个文档都有一个“messages”数组,该数组映射到消息正文、createdAt和发送者的用户名。聊天室中的所有用户都有第二个数组 如何返回messages数组的最后10个元素 代码: exports.getChat=(请求、回复)=>{ 让chatData={}; db.doc(`/chats/${req.params.chatId}`) .get() 。然后((doc)=>{ 如果(!doc.存在){ 返回res.status(404.json)({err

我正在尝试在聊天中获取所有消息。每个文档都有一个“messages”数组,该数组映射到消息正文、createdAt和发送者的用户名。聊天室中的所有用户都有第二个数组

如何返回messages数组的最后10个元素

代码:

exports.getChat=(请求、回复)=>{
让chatData={};
db.doc(`/chats/${req.params.chatId}`)
.get()
。然后((doc)=>{
如果(!doc.存在){
返回res.status(404.json)({error:“Chat not found.”});
}
chatData=doc.data();
chatData.chatId=doc.id;
返回数据库
.收藏(“聊天”)
.where(“chatId”,“==”,请求参数chatId)
.get();
})
。然后((数据)=>{
chatData.messages=[];
data.forEach((doc)=>{
chatData.messages.push(doc.data());
});
返回res.json(chatData);
})
.catch((错误)=>{
控制台错误(err);
json({error:err.code});
});
};

到目前为止,我的代码返回一个空消息数组。

查询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      
    })