首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在Firebase中查询数组的映射时,数组为空

在Firebase中查询数组的映射时,数组为空
EN

Stack Overflow用户
提问于 2020-08-09 09:08:19
回答 1查看 102关注 0票数 2

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

如何返回消息数组的最后10个元素?

代码:

代码语言:javascript
复制
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 });
    });
};

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

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-08-09 09:34:52

当查询Firestore时,不可能指示查询从数组字段中过滤出项目。您必须读取整个数组字段,然后决定如何处理该数组中的项。因此,这意味着第二个查询在这里没有帮助。在第一个文档快照中,您已经拥有了所需的所有内容。

代码语言:javascript
复制
  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      
    })
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/63321574

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档