0

Here is my code. I have two input parameters authUser and chatUser. I have a record called Chats, with a List field called users. I want to query and get the document where the List field users contains BOTH authUser and chatUser.

import 'package:cloud_firestore/cloud_firestore.dart';

Future<ChatsRecord> getChatDocFromChatUserAuthUser(
  DocumentReference? chatUserRef,
  DocumentReference? authUserRef,
) async {
  // Add your function code here!

  ChatsRecord chatDoc = await FirebaseFirestore.instance
      .collection('chats')
      .where("users", arrayContains: chatUserRef)
      .where("users", arrayContains: authUser)
      .get()
      .then((snapshot));

  return chatDoc;
}

Here is the error I get from trying the solution below:

lib/custom_code/actions/get_chat_doc.dart:23:34:
Error: A value of type 'List<QueryDocumentSnapshot<Object?>>' can't be returned from an async function with return type 'Future<List<ChatsRecord>>'.
 - 'List' is from 'dart:core'.
 - 'QueryDocumentSnapshot' is from 'package:cloud_firestore/cloud_firestore.dart' ('/root/.pub-cache/hosted/pub.dartlang.org/cloud_firestore-4.2.0/lib/cloud_firestore.dart').
 - 'Object' is from 'dart:core'.
 - 'Future' is from 'dart:async'.
 - 'ChatsRecord' is from 'package:counter_party/backend/schema/chats_record.dart' ('lib/backend/schema/chats_record.dart').
  return (await snapshots.first).toList();
                                 ^
Error: Compilation failed.
satchel
  • 405
  • 5
  • 16
  • So basically you need to need to `arrayContains` calls? Is that correct? – Alex Mamo Jan 03 '23 at 08:22
  • yes, I know that what I wrote is not permitted, but I am describing the desired behavior. I would like to check whether BOTH chatUserRef AND authUser are in the users field which is a list. – satchel Jan 04 '23 at 01:10

1 Answers1

1

You should try using conditions from QuerySnapshots by :

CollectionReference chatDoc = Firestore.instance.collection('chats');
final snapshots = chatDoc.snapshots().map((snapshot) => snapshot.documents.where((doc) => doc["users"] == chatUserRef || doc["users"] == authUser));

return (await snapshots.first).toList();
Risheek Mittal
  • 1,077
  • 2
  • 18