I am trying to retrieve posts from a list of accounts that a user follows, but am unsure on the best way to do so? I have implemented a the same structure from this stack overflow answer, as I found it sensible for what I was trying to create (see below).
Firestore-root
|
--- users (collection)
| |
| --- uid (documents)
| |
| --- name: "User Name"
| |
| --- email: "email@email.com"
|
--- following (collection)
| |
| --- uid (document)
| |
| --- userFollowing (collection)
| |
| --- uid (documents)
| |
| --- uid (documents)
|
--- posts (collection)
|
--- uid (documents)
|
--- userPosts (collection)
|
--- postId (documents)
| |
| --- title: "Post Title"
| |
| --- date: September 03, 2018 at 6:16:58 PM UTC+3
|
--- postId (documents)
|
--- title: "Post Title"
|
--- date: September 03, 2018 at 6:16:58 PM UTC+3
However, I am struggling to understand the best way to retrieve a list of posts where its document UID is the same as the one a user is following.
I have attempted to get all the users followers and then for each document, loop over it using another get, but haven't found a successful solution. An example of this code can be seen below:
var userFollowingList = [User]()
db.collection("Following").document(currentUserUID).collection("userFollowing")
.getDocuments() { (querySnapshot, err) in
if let err = err {
print("Error getting documents: \(err)")
completion(false)
} else {
for document in querySnapshot!.documents {
print("\(document.documentID) => \(document.data())")
userFollowingList = querySnapshot!.documents.compactMap { querySnapshot -> User? in
return try? querySnapshot.data(as: User.self)
}
}
for user in userFollowingList {
db.collection("Posts")
.getDocuments() { (tripQuerySnapshot, err) in
if let err = err {
print("Error getting documents: \(err)")
completion(false)
} else {
for document in tripQuerySnapshot!.documents {
print("\(document.documentID) => \(document.data())")
self.followingTrips = querySnapshot!.documents.compactMap { querySnapshot -> Trip? in
return try? querySnapshot.data(as: Trip.self)
}
}
}
}
}
}
What is the most efficient way to achieve this? Thanks.
30/03/2020 UPDATE:
I ended up looping over each userID in the following list and returning all the posts for the users, but I'm still not sure if this is the best way. See example below:
let userFollowingIDs = ["01","02","03"]
for id in userFollowingIDs {
db.collection("Trips").document(id).collection("userPosts")
.getDocuments() { (querySnapshot, err) in
if let err = err {
print("Error getting documents: \(err)")
completion(false)
} else {
for document in querySnapshot!.documents {
print("\(document.documentID) => \(document.data())")
self.followingTripsList = querySnapshot!.documents.compactMap { querySnapshot -> Trip? in
return try? querySnapshot.data(as: Trip.self)
}
}
completion(true)
}
}
}