Home > Enterprise >  Firebase Firestore adding data into a 2 collections, with the same values (mainly the uid)
Firebase Firestore adding data into a 2 collections, with the same values (mainly the uid)

Time:06-27

Basically I have 2 collections 'Bookings' and 'Users'. The 'Bookings' collection shows all bookings created by every user, and can only be accessed by an admin account, while the user.bookings collection would show only the bookings created by that specific user.

I have been able to add a booking into the 'Bookings' collection but am currently stuck on how to retrieve that specific booking, and add it into another 'Bookings' collection under that user, without iterating through the entire 'Bookings' collection and then adding the corresponding booking to the user.bookings collection.

Is there a way to do one .add that would create the same uid, or is iterating over the 'Bookings' collection the only way?

FirebaseFirestore.instance.collection('bookings')
          .add({
            'location': selectedLocation,
            'time': selectedTime, 
            'email': user.email,
            'phoneNumber': 08111111111
          })

Added an example of the User collection model

User: {
    name:
    bookings: { 
        booking1: {
            location:
            time:
            email:
            phoneNumber:
        }
        booking2: {
            location:
            time:
            email:
            phoneNumber:
        }
    }
    etc:
}

CodePudding user response:

It would be better if: While you adding the booking data to the "Booking" collection, you also need to add it also to the user.booking collection.

CodePudding user response:

Since the bookings collection can only be accessed by an admin account, a classical solution in your case (denormalization in a NoSQL Database) is to use a Cloud Function to create the Booking document in the users/{userID}/bookings subcollection when a new Booking is created in the bookings collection.

Something along the following lines:

exports.duplicateBooking = functions
    .firestore
    .document('bookings/{docId}')
    .onCreate((snap, context) => {

        const userId = ....; // Not clear from your question how you define that. You should probably add it to the booking doc.

        const bookingData = snap.data();

        return admin
            .firestore()
            .collection(`users/${userId}/bookings)
            .add({
                 'location': bookingData.location,
                 'time': bookingData.time, 
                 'email': bookingData.email,
                 'phoneNumber': bookingData.phoneNumber
          });

    });

Another possibilities would be to keep a unique bookings collection with a set of Security Rules that allows a user to read his own bookings. In this case, remember that rules are not filters when you write the corresponding query.

  • Related