I have a collection called Channels and inside it I have a sub collection called messages , so I want to filter the channel collection then I want to fetch the messages from it ?
FirebaseFirestore.instance
.collection('Channels') >> where(id = user.uid) <<<<< I want to filter this
.doc()
.collection("messages")
.orderBy("createdAt")
.snapshots(),
*any help will be appreciated ^^
error : error message
The method 'doc' isn't defined for the type 'Query'. Try correcting the name to the name of an existing method, or defining a method named 'doc'.
CodePudding user response:
According to this link you should use the where
method. Combine that with firebase.flutter.dev docs (heading with relevant example here), you should be able to accomplish this using something like:
FirebaseFirestore.instance
.collection('Channels')
.where('id', isEqualTo: user.uid)
Also is channelID same with senderID? If the answer is yes, do you need both (and are you sure that is the structure you want)? :)
CodePudding user response:
A Firestore query can only access documents from a single collection, or from a group of collections all with the same name. So you can't filter documents from messages
based on fields in their parent Channels
document.
What you can do is add the relevant field to each messages
document, e.g. in a field named channelUID
. Then you can use a collection group query to query all messages
collections:
FirebaseFirestore.instance
.collectionGroup("messages")
.orderBy("createdAt")
.where("channelUID", isEqualTo: user.uid)
.snapshots(),
CodePudding user response:
The problem is that the doc()
is empty, so FB does not know which doc to go into.
Just add the id of the channel inside the doc()
, like so:
FirebaseFirestore.instance
.collection('Channels')
.doc(recieverID)
.collection('messages')
.orderBy('createdAt')