Hi I'm trying to fetch some posts by their popularity, I need them to be posts from this month and to be ordered by the number of saved.
func fetch() {
let query = Firestore.firestore().collection("posts").whereField("timestamp", isGreaterThanOrEqualTo: Date().ThisMonth).order(by: "Likes", descending: true)
query.getDocuments { snapshot, error in
if error != nil {
print(error?.localizedDescription as Any)
return
}
guard let documents = snapshot?.documents else { return }
let data = documents.compactMap({ try? $0.data(as: Post.self) })
self.posts.append(contentsOf: data)
}
}
But when I run the code I get the following:
*** Terminating app due to uncaught exception 'FIRInvalidArgumentException', reason: 'Invalid query. You have a where filter with an inequality (notEqual, lessThan, lessThanOrEqual, greaterThan, or greaterThanOrEqual) on field 'timestamp' and so you must also use 'timestamp' as your first queryOrderedBy field, but your first queryOrderedBy is currently on field 'Likes 'instead.' terminating with uncaught exception of type NSException
I already tried to do it this way but it still won't let me:
func fetch() {
let query = Firestore.firestore().collection("posts").order(by: "timestamp", descending: true).whereField("timestamp", isGreaterThanOrEqualTo: Date().ThisMonth).order(by: "Likes", descending: true)
query.getDocuments { snapshot, error in
if error != nil {
print(error?.localizedDescription as Any)
return
}
guard let documents = snapshot?.documents else { return }
let data = documents.compactMap({ try? $0.data(as: Post.self) })
self.posts.append(contentsOf: data)
}
}
Is there a way to order the posts in this way? What I want is to order them by popularity but only the posts of this month, not all the posts
Thanks!
CodePudding user response:
Error says that you have wrong field name isGraterThenOrEqualTo: it should be greaterThanOrEqual: and bad order of .order() method. Try bellow example.
let query = Firestore.firestore().collection("posts")
.order(by: "Likes", descending: true)
.whereField("timestamp", greaterThanOrEqual: Date().ThisMonth)
.order(by: "timestamp", descending: true) // first timestamp becouse of ".whereField()"
