Tan Li Tung
Tan Li Tung

Reputation: 11

How to write Firebase Realtime Database to Firestore automatically?

I am currently doing a project that uses Arduino to collect data and store the data in cloud and display the data on cloud on mobile app. From what I have tried, Arduino can only upload data to Firebase realtime database, but my Flutter mobile app needs the data to be stored in Firestore. Is there any way to write firebase realtime database data into Firestore automatically when there is changes in the realtime database?

This is the realtime database structure: realtime database structure

and I would like to append the data into respective field in Firestore like this: firestore structure

I have tried to read the data every 5 seconds and write it to Firebase but it does not seems like very efficient:

final userDbRef = FirebaseDatabase.instance.ref("user/");
 String uid = globals.uid;

 Stream<DatabaseEvent> stream = userDbRef.onValue;

 // Subscribe to the stream!
 var subscription = stream.listen((DatabaseEvent event) {
   // print('Listening');
   dynamic values = event.snapshot.value;
   final data = new Map<String, dynamic>.from(values);

   globals.temp = data['temp'];
   globals.hr = data ['hr'];
   globals.spo2 = data['spo2'];
   globals.position = data['position'];
   globals.time = DateTime.parse(data['time']);
 });

 subscription.pause();

 String date = DateTime.now().add(const Duration(hours: 8)).toString().substring(0, 10);

 dynamic result = await DatabaseService(uid: uid).getUserData('patient');
 if (result[date].toString() == 'null') {
   await DatabaseService(uid: uid).updateSingleUserData('patient', {
     date: {
       'time': ['${date} 00:00:00.000'],
       'hr': [95],
       'temp': [36.5],
       'spo2': [98],
       'position': ['lying'],
     },
   });
 } else {
   List timeList = result[date]['time'];
   List hrList = result[date]['hr'];
   List tempList = result[date]['temp'];
   List spo2List = result[date]['spo2'];
   List positionList = result[date]['position'];

   if ((!timeList.contains(globals.time.toString())) & (globals.time.toString() != 'null')) {
     timeList.add(globals.time.toString());
     hrList.add(globals.hr);
     tempList.add(globals.temp);
     spo2List.add(globals.spo2);
     positionList.add(globals.position);

    await DatabaseService(uid:uid).updateSingleUserData('patient', {
       date: {
         'time': timeList,
         'hr': hrList,
         'temp': tempList,
         'spo2': spo2List,
         'position': positionList,
       },
     });
   }
 }
 subscription.resume();

Thank you.

Upvotes: 1

Views: 494

Answers (1)

Renaud Tarnec
Renaud Tarnec

Reputation: 83048

Is there any way to write firebase realtime database data into Firestore automatically when there is changes in the realtime database?

Yes, a common approach is to use a Cloud Function that is automatically triggered each time a new node is added to the Realtime Database. The Cloud Function is executed in the back-end, i.e. on the Firebase/Google Cloud infrastructure, and therefore you don't need to write any code in your Flutter app for this data mirroring/transfert.

Here is a simple example with generic paths:

// The Cloud Functions for Firebase SDK to create Cloud Functions and set up triggers.
const functions = require('firebase-functions');

// The Firebase Admin SDK to access Firestore.
const admin = require('firebase-admin');
admin.initializeApp();


exports.duplicateToFirestore = functions.database.ref('/myRTDBPath/{pushId}')
    .onCreate((snapshot, context) => {
      // Grab the current value of what was written to the Realtime Database.
      const nodeVal = snapshot.val();

      // Write it to a Firestore collection

      return admin.firestore().collection('myFirestoreCollection').add(nodeVal);

    });

I let you do the work of transformation of the RTDB node value to the Firestore document structure you are looking for.

Upvotes: 2

Related Questions