【问题标题】:Firestore: Searching the element inside document array if it exists or notFirestore:搜索文档数组中的元素是否存在
【发布时间】:2020-01-05 13:38:07
【问题描述】:

我正在收集一些文件。每个文档都包含一些带有字符串的数组。我想知道给定的字符串是否存在于特定的文档数组中。我已经看到使用数组包含查找文档的查询。但是我有一个文档,我只想查询该字符串是否存在于该文档数组中?

 var dbRef = dbConnection.db.collection('posts').doc(req.body.post_id);
dbRef.where('likes', 'array-contains', req.body.user_id).get()
    .then(data => {
        console.log(data);
    })
    .catch(err => {
        console.log(err);
    })

我有一个具有特定 ID 的文档。我知道文档 ID。该文档包含名为 likes 的数组。该数组将存储一些字符串。我想知道该字符串是否存在于该数组中?我收到以下错误

TypeError: dbRef.where is not a function

然后我尝试不提供文档 ID。有效。它退回了文件。但我想在文档数组中搜索

【问题讨论】:

  • 请贴出您目前尝试过的代码和问题区域。
  • @AshishModi 我编辑了这个问题。请检查我的查询是否有任何问题。
  • 如果您想知道单个文档中的数组字段是否包含某些值,只需阅读文档并检查代码中的数组即可。

标签: node.js google-cloud-firestore


【解决方案1】:

您的dbRef 指向(单个)文档,您无法查询文档。

如果您要查询posts 集合中的文档,您正在寻找:

var dbRef = dbConnection.db.collection('posts');
dbRef.where('likes', 'array-contains', req.body.user_id).get()
  ...

您可以通过以下方式查询文档 ID 和数组包含:

db.collection('books').where(firebase.firestore.FieldPath.documentId(), '==', 'fK3ddutEpD2qQqRMXNW5').get()
var dbRef = dbConnection.db.collection('posts');
dbRef
  .where(firebase.firestore.FieldPath.documentId(), '==', req.body.post_id)
  .where('likes', 'array-contains', req.body.user_id).get()
    ...

或者,您可以简单地使用原始代码读取文档,然后在客户端检查该数组是否仍然包含该字段:

var dbRef = dbConnection.db.collection('posts').doc(req.body.post_id);
dbRef.get()
    .then(doc => {
        if (doc.data().likes.indexOf(req.body.user_id) >= 0) {
          ... the post is liked by the user
        }
    })
    .catch(err => {
        console.log(err);
    })

【讨论】:

    猜你喜欢
    • 2022-01-05
    • 2019-08-03
    • 1970-01-01
    • 1970-01-01
    • 2020-07-24
    • 2022-01-14
    • 1970-01-01
    • 2020-06-17
    • 2018-08-05
    相关资源
    最近更新 更多