Home > Back-end >  Querying FireBase FireStore Document in Flutter
Querying FireBase FireStore Document in Flutter

Time:05-21

I wants to achieve one query which i'm trying for few hours in FireStore Database, Please check the below image,

enter image description here

The Query I want to do is, In the document which I marked, will have a list of group id (combination of 2 userIds in each , userId1-userId2), I want to query this document by having one userId that contains in the group id (before or after hyphen) and returns a list of snapshots , which should be used for StreamBuilder in a list widget.

For Example: I may have 'abcdefghijkl' userId, I want to check each document ID that contains this userId, and returns a list of snapshots which matches.

Thanks in Advance!

CodePudding user response:

I don't think the query you want is possible, since there is no operation to check if a document id contains something. I would recommend adding a participants array to the document and than use an array-contains query, see also here.

CodePudding user response:

There are several ways to achieve what you're after - a list of users relating to a given document - but I think you should rethink your data structure first. Each message document should have a users field that is an array of Firestore document IDs which would contain 1 or more document IDs of the users that this message relates to.

With that, you can easily query the database for all messages where a given user is referenced:

final messages = db
  .collection('messages')
  .where('users', arrayContains: userId)
  .get();

BTW, to take things a step further, I would structure my data like this:

user {
  displayName: '',
  email: '',
  messages: [
    {
      authorId: userId,
      content: '',
      users: [userId, ...],
      sentOn: '',
    },
    ...
  ]
}

With this you can do two things:

  1. Fetch all messages created by the user:
final userMessages = db.doc(userId).collection('messages').get();
  1. Fetch all messages where user participated:
final allUserMessages = db
  .collectionGroup('messages')
  .where('users', arrayContains: userId)
  .get();

Check out the Firestore docs, as they have plenty of examples there.

  • Related