首页 > 解决方案 > 如何进行正确的搜索查询以在 firebase 上的数组中查找对象 - firestore

问题描述

我正在尝试通过做一些事情来学习firebase,所以我可能错误地建模了我的数据库。无论如何,我想知道是否有办法搜索所有具有特定电子邮件价值的评论。让我向您展示我的数据库的结构在此处输入图像描述

我尝试阅读文档,并尝试了一些不起作用的方法,例如:

   const fetchComments = async () => {
   const commentRef = await db.collection("comments")

   return commentRef.where("email", '==', "123@123.com").get()
}


   fetchComments().then(function (querySnapshot) {
    querySnapshot.forEach(function (doc) {

        console.log(doc.id, ' => ', doc.data());
    });})

但是记录不会返回任何东西,如果你记录查询快照,我当然会得到一个带有一堆东西的对象,但它似乎没有数据 在此处输入图像描述

所以我想知道,首先,有没有办法获取所有带有特定电子邮件的评论?或者,如果基本上我以错误的方式构建了所有数据,并且无法获取它们。

谢谢

标签: javascriptdatabasefirebasegoogle-cloud-firestore

解决方案


需要注意的重要一点是,firestore 将始终从查询中返回整个文档。

截至今天的 Firebase 文档<允许您在 where 子句中添加以下条件: , <=, ==, >, >=, array-contains,inarray-contains-any.

最接近您的用例的一个条件是

数组包含: 如果您的文档中存储了一个数组,例如:

liked_by: ["user1", "user2", "user3"]

您可以使用 where 子句运行查询,.where('liked_by', 'array-contains', 'user1')它将返回所有文档liked_by,其中包含一个包含字符串“user1”的数组。如果您将对象存储在数组中,例如

comments: [
  {
    text: "comment",
    user_id: "user1",
    date: "dd/mm/yyyy"
  }, ...
]

您必须将整个对象放在 where 子句中,例如: .where('comments', 'array-contains', {text: "comment", "user_id: "user1", date: "dd/mm/yyyy"})这将返回包含名为 comments 的数组并具有与 where 子句中的确切对象相同的所有文档。

在您的情况下,每个文档中都有一组注释,因此除非您碰巧知道整个对象,否则您将无法查询此类文档。

如果这些文档 ID (1,2,3...) 对您很重要,我建议您采用以下结构:

comments:{ // collection name
  "random_document_id_created_by_firestore": { 
// doc ids are assigned automatically by firestore when you use the add method. 
// refer: https://firebase.google.com/docs/firestore/manage-data/add-data#add_a_document
    "comment": "comment text",
    "datePosted": "dd/mm/yyyy",
    "email": "123@123.com",
    "id": 9993,
    "docId": 1 // add the key name (docId) as per your choice, e.g. postId
  }, ...
}

然后,您可以在查询中链接多个 where 子句以根据需要过滤数据: .where('docId', '==', 1).where('email', '==', '123@123.com').get()


推荐阅读