简体   繁体   English

按对象查询Firestore集合

[英]Query Firestore collection by object

I create a collection called "books", in it I made an object (aka. dict) called "users". 我创建了一个名为“books”的集合,在其中我制作了一个名为“users”的对象(又名.dict)。 That object looks like this: 该对象看起来像这样:

users: {
    5PPCTcdHOtdYjGFr7gbCEsiMaWG3: firebase.firestore.FieldValue.serverTimestamp()
}

Now I want to query all books that belong to a certain user. 现在我想查询属于某个用户的所有书籍。 I tried this: 我试过这个:

this.db
  .collection('books')
  .where(`users.${this.state.currentUser.uid}`, '>', 0)
  .onSnapshot(querySnapshot => {
      ...

I never get any documents returned. 我从来没有收到任何文件。 I'm sure the there is something it should match. 我确定它应该匹配。

Firestore控制台的屏幕截图

To check my sanity, if I remove the where(...) part, I do get documents. 为了检查我的理智,如果我删除where(...)部分,我会得到文件。 Just that I get documents for all users. 只是我为所有用户提供了文档。

I console logged that string in the .where() and it looks right. 我控制台在.where()记录了该字符串,它看起来正确。

I can't get this to work with .where() either, but it seems to work using .orderBy() , replacing: 我也无法使用.where() ,但似乎使用.orderBy() ,替换:

.where(`users.${this.state.currentUser.uid}`, '>', 0)

with

.orderBy(`users.${this.state.currentUser.uid}`)

You're query is wrong because you are comparing a date object with a number, therefore two different things. 您的查询是错误的,因为您正在将日期对象与数字进行比较,因此有两个不同的事情。 You can check it by running these two lines of code below. 您可以通过在下面运行以下两行代码来检查它。

  console.log(typeof(firebase.firestore.FieldValue.serverTimestamp()))
  console.log(typeof(0))

So you have two options: 所以你有两个选择:

1 - You can compare date objects with data objects like below. 1 - 您可以将日期对象与下面的数据对象进行比较。

this.db
  .collection('books')
  .where(`users.${this.state.currentUser.uid}`, '>', new Date(0))
  .onSnapshot(querySnapshot => {
      ...

2 - Or you can save your date in milliseconds and compare it with a number. 2 - 或者您可以以毫秒为单位保存日期并将其与数字进行比较。

users: {
    5PPCTcdHOtdYjGFr7gbCEsiMaWG3: new Date().getTime();
}

 this.db
      .collection('books')
      .where(`users.${this.state.currentUser.uid}`, '>', 0)
      .onSnapshot(querySnapshot => {
          ...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM