How to check if a document exists with a given id in firestore, without costing money?

感情迁移 提交于 2020-06-13 05:50:49

问题


I have a scenario where I have the phone number of the user and I want to check if the user is already registered on my app or not. To do this, I have a collection in firestore. In this collection, I the contact number of the individual user as a document. Whenever the user goes on the app and enters his mobile number, the app sends the request to search a specific document using

final snapShot = await Firestore.instance.collection('rCust').document(_phoneNumberController.text).get();

My database structure is as follows

Due to this, my firestore billing is spiking up really fast. In just with 4-5 queries, my number of reads spiked from 75 to 293. It would be great if anyone could guide me in how to do this efficiently.


回答1:


To check if a document exists, you can use the .exists propety in the documentSnapshot, in your case:

if(snapShot.exists) {

}

From that query, you are selecting a single document, not a collection.

Because we can't see other code, I am assuming that your firestore usage is actually not spiking due to your query, but due to you viewing your documents in the firebase web console. Viewing the console on the web also incurrs billing, and lists documents 300 at a time.




回答2:


If you want to know if a document definitely exists on the server, it will always cost you a document read. There is currently no way to avoid this cost. It's the cost of accessing the massively scalable index that allows you to find 1 document among potentially billions.

You could try to query your local cache first, which is doesn't cost anything. You do this by passing a Source.cache argument to get(). If you want to make the assumption that presence in the local cache always means that the document exists on the server, that will save you one document read. However, if the document is deleted on the server, the local cache query will be incorrect. You will still have to query the server to know for sure.




回答3:


You can check it doing this

if(snapShot.getResults().exists()) {
  // ...
}

if you don't want to set each time you send the phoneNumber to the document but instead updating just that number, you should use update("fieldToUpdate",value) on the document you are setting the data instead of using .set(value)



来源:https://stackoverflow.com/questions/60919858/how-to-check-if-a-document-exists-with-a-given-id-in-firestore-without-costing

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!