0
votes

I'm working with Flutter and Firebase and came up with the following Firebase structure.

Room collections

Room and user collections:

2

I want users to be able to read and write their data. And I wrote the following rules:

rules

For getting rooms, I've following code in Flutter:

     Stream<List<RoomModel>> getRooms() {
        var user = firebaseAuth.currentUser;
        return _db
            .collection('rooms')
            // .where("userId", "==", user.uid)
            .snapshots()
            .map((snapshot) => snapshot.docs
                .map((document) => RoomModel.fromFirestore(document.data()))
                .toList());
      }

Room Model:

    // import 'package:firebase_auth/firebase_auth.dart';
    
    class RoomModel {
      final String roomId;
      final double price;
      final String location;
      final String userId;
    
      RoomModel(this.roomId, this.price, this.location, this.userId);
    
      Map<String, dynamic> toMap() {
        // final firebaseAuth = FirebaseAuth.instance;
        // var user = firebaseAuth.currentUser;
        return {
          'roomId': roomId,
          'price': price,
          'userId': userId,
          'location': location,
        };
      }
    
      RoomModel.fromFirestore(Map firestore)
          : roomId = firestore['roomId'],
            price = firestore['price'],
            location = firestore['location'],
            userId = firestore['userId'];
    }

But still, I'm getting all the rooms, including other user's room.

And later I also wanted to read all the rooms. How should I do it?

1

1 Answers

1
votes

I would add subcollections. users/USERID/rooms/. To get All rooms use collectionGroup by adding an index

 var myUserId = firebase.auth().currentUser.uid;
 var myReviews = firebase.firestore().collectionGroup('room')
   .where('userId', '==', myUserId);
 myReviews.get().then(function (querySnapshot) {
    // Do something with these rooms!
 })

Read More here.

https://firebase.google.com/docs/firestore/query-data/indexing?authuser=0 https://firebase.googleblog.com/2019/06/understanding-collection-group-queries.html