简体   繁体   English

Ionic 4 Firestore 是否可以只读取文档的一部分?

[英]Ionic 4 Firestore is it possible to read only a part of a document?

I hope you're ok!我希望你没事! Thanks for reading.谢谢阅读。

Edited the question.编辑了问题。

Say one document in firestore has objects stored as follows:假设 firestore 中的一个文档的对象存储如下:

someida: {name: steve, alias: cap, etc}
someidb: {name: tony, alias: iron, etc}
someidc: {name: nat, alias: black, etc}
someidetc

And I know all the "someids", I'm guessing the answer might be no, but我知道所有的“someids”,我猜答案可能是否定的,但是

Is it possible to write a query that would read only what's inside one of those someids'?是否可以编写一个查询,只读取其中一个 someids 中的内容?

Currently I can get the data I need but after reading all the document and coding to find it and was wondering if it would be possible to avoid that, and just read the contents of one object since I have the "someid".目前我可以获得我需要的数据,但是在阅读了所有文档和编码以找到它之后,我想知道是否有可能避免这种情况,因为我有“someid”,所以只读取一个对象的内容。

Already a great reply was posted, just wondering if there's any other suggestion.已经发布了一个很好的回复,只是想知道是否还有其他建议。

Thank too many in advance!提前感谢太多! Best!最好的事物!

The easiest way would be to restructure your document a bit.最简单的方法是稍微重组您的文档。 Instead of storing each "someid" as a property, create an array of maps as a single property in the Firestore document.不是将每个“someid”存储为一个属性,而是在 Firestore 文档中创建一个映射数组作为单个属性。 For example, the following would be how your document would look like:例如,您的文档如下所示:

ids: [
      {id: someida, name: steve, alias: cap, etc},
      {id: someidb, name: tony, alias: iron, etc},
      {id: someidc, name: nat, alias: black, etc}
]

where id , name , alias are properties of an object, and ids is an array of the type of that object.其中idnamealias是对象的属性,而ids是该对象类型的数组。

Now, you can easily extract the data you need from this array in your app.现在,您可以轻松地从应用程序中的这个数组中提取您需要的数据。 Since you are probably using AngularFire, you can retrieve this document by calling the following API in ngOnInit:由于您可能正在使用 AngularFire,您可以通过在 ngOnInit 中调用以下 API 来检索此文档:

ngOnInit() {
  this.users = await this.angularFirestore.collection(YOUR_COLLECTION).doc(YOUR_DOCUMENT).get()
    .pipe(map(result => result.data().ids as Array<OBJECT_TYPE>))
    .toPromise();
}

getAlias(requestedId: string) {
  return this.users.find(ob => ob.id === requestedId).alias;
}

isUserAvailable(requestedId: string): boolean {
  return !!this.users.find(ob => ob.id === requestedId);
}

To get the alias of "someidc", you can call the following function: this.getAlias("someidc")要获取“someidc”的别名,可以调用以下函数: this.getAlias("someidc")

And to find out whether certain id is available or not: this.isUserAvailable("someida")并找出某个 id 是否可用: this.isUserAvailable("someida")

Of course, make sure to call those functions after you've made your call to Firestore.当然,请确保在调用 Firestore 后调用这些函数。 ngOnInit should take care of that for you. ngOnInit 应该为你处理这个问题。

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

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