[英]How do I get the position of a document in Firebase Cloud Firestore using swift?
I created a database in CloudFirestore, now I want to retrieve the position number of the documents from it (ie: jolly's position should be "2"), I tried to do it using the.whereField but I was unable to read the querySnapshot.count outside the query.我在 CloudFirestore 中创建了一个数据库,现在我想从中检索文档的 position 编号(即:jolly 的 position 应该是“2”),我尝试使用.whereField 来执行此操作,但我无法读取 querySnapshot。在查询之外计数。
I am trying to do it like this:我正在尝试这样做:
db.collection("TimeSlots")
.whereField("written", isEqualTo: true)
.getDocuments() { (querySnapshot, err) in
if err != nil {
print("Error getting documents: (err)")
} else {
position = querySnapshot?.count as? Int
}
}
so here as soon as an entry is added i am getting its position in the "position" variable but I am unable to use the position value outside this method.所以在这里,只要添加一个条目,我就会在“位置”变量中得到它的 position,但我无法在此方法之外使用 position 值。
Please and thank you!谢谢,麻烦您了!
Firestore documents don't have a "position". Firestore 文档没有“位置”。 The order of documents you see in the console is always going to be alphabetical (actually lexicographically ) by document ID.
您在控制台中看到的文档顺序总是按文档 ID 的字母顺序(实际上是字典顺序)。 There are no queries that let you specify any index into a collection, as those types of operations do not scale massively as Firestore requires.
没有查询可以让您在集合中指定任何索引,因为这些类型的操作不会像 Firestore 需要的那样大规模扩展。
Here is how I managed to index position of documents from the collection (Using question's cloud firestore as an example):-这是我设法从集合中索引 position 文档的方法(以问题的云存储库为例):-
db.orderBy("time", Query.Direction.DESCENDING)
.get()
.addOnCompleteListener(new OnCompleteListener<QuerySnapshot>()
{
@Override
public void onComplete(@NonNull Task<QuerySnapshot> task)
{
if(task.isSuccessful())
{
if(Objects.requireNonNull(task.getResult()).size() > 0)
{
int i = 0; //temporary index
Map<Integer, Object> _docList = new HashMap<>(); // A hashMap to store document id
for(DocumentSnapshot _documentSnapshot : Objects.requireNonNull(task.getResult()))
{
_docList.put(i, _documentSnapshot.getId());//Store temporary index (i) mapping to each document
//Checks if i equals to the documentIndex needed.
//Let's say documentIndex is 2 (Declared as a parameter of a method).
if(i == documentIndex)
{
//Do something with the document at that index.
_collectionReference.document(_documentSnapshot.getId()).delete(); //Here I am deleting the jolly document.
return;
}
i++; //Increase the temp index if the statement is not true
}
}
}
}
});
I have commented the code for easy understandability.为了便于理解,我对代码进行了注释。 Hope this will help someone out there.
希望这会帮助那里的人。 Though I used
Java
hope the Swift
guys will understand.虽然我使用了
Java
希望Swift
的人会理解。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.