【问题标题】:Get all documents from collection where ID contains certain ref从集合中获取 ID 包含特定 ref 的所有文档
【发布时间】:2018-12-12 19:31:48
【问题描述】:

是否可以获取 ID 包含特定值的所有文档。我正在使用 Angular 7。

我试过 db.collection('items').where.. 但这不受支持。

例子

(collection)
/items
     (doc)
     /green apple
     /red apple
     /banana
     /melon

我能否对集合“items”进行查询,以检索 ID 包含“apple”的所有文档。我似乎找不到可行的解决方案。

【问题讨论】:

  • 您是说您只想通过其唯一 ID 获取文档吗?无需查询即可。
  • 我会遵从@DougStevenson,但我的建议是在文档中创建一个与名称匹配的字段(并且可能跳过自定义名称以支持谷歌生成的乱码),然后查询在该名称字段值上。
  • @danh 正如您所说,当您没有唯一可识别的字符串来表示文档时,“乱码”实际上很重要。您可以在需要时使用它,但如果您已经拥有唯一 ID,则没有义务。也就是说,想出唯一的字符串并不总是那么容易或方便。
  • 谢谢@DougStevenson。我的意思不是贬义的胡言乱语,更异想天开地指代系统生成的唯一 ID。我认为 op 确实需要一个用于查询的字段,而不是(或除此之外)一个可读的名称。
  • Firestore 允许前缀匹配,但没有“包含”运算符。因此,除非“apple”在开头,否则您要查找的内容是不可能通过查询实现的。见stackoverflow.com/questions/47115422/…

标签: javascript google-cloud-firestore


【解决方案1】:

这是我要做的:在创建(或更新)文档时,使用您将用作标题的字符串来创建另一个属性,也许称之为searchTerms

let docName = 'green apple';
let ref = /* some path */.collection('items').doc();  // optionally use docName here
let doc = { /* however you initialize your doc */ }

doc.searchTerms = docName.split(' ').reduce((acc, term) => {
      acc[term] = true;
      return acc;
    }, {});
    // that will set searchTerms to { 'green':true, 'apple':true }

ref.set(doc)

稍后,您可以像这样查询这些文档:

let targetTerm = 'apple'
let key = `searchTerms.${targetTerm}`;
let query = /* some path */.collection('items').where(key, '==', true)

8月份的产品introduced support for searching arrays,所以创建对象的时候可以跳过reduce,在query上问where-contains,像这样:

// as before
doc.searchTerms = docName.split(' ');
ref.set(doc)

及以后:

let targetTerm = 'apple'
let query = /* some path */.collection('items').where('searchTerms', 'array-contains', targetTerm)

您还可以使用云触发器onCreate 来构建搜索词字段,因此代码中完成创建的所有点都不必担心这一点。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-12-27
    • 1970-01-01
    • 2020-08-09
    • 1970-01-01
    • 1970-01-01
    • 2020-05-26
    • 2019-09-17
    相关资源
    最近更新 更多