0

I've been trying out MongoDB as database for my Flutter project lately, since I want to migrate from pure Firebase database (some limitations in Firebase are an issue for my project, like the "in-array" limit of 10 for queries).

I already made some CRUD operations methods in some Firebase Cloud Functions, using MongoDB. I'm now able to save data and display it as a Future in a Flutter App (a simple ListView of Users in a FutureBuilder).

My question is : how would it be possible to create a StreamBuilder thanks to MongoDB and Firebase Cloud Functions ? I saw some stuff about watch collection and Stream change but nothing clear enough for me (usually I read a lot of examples or tutorial to understand).

Maybe some of you would have some clues or maybe tutorial that I can read/watch to learn a little bit more about that subject ?

For now, I have this as an example (NodeJS Cloud Function stored in Firebase), which obviously produces a Future in my Future app (not realtime) :

exports.getUsers = functions.https.onCall(async (data, context) => {
    const uri = "mongodb+srv://....";
    const client = new MongoClient(uri);
    await client.connect();
    var results = await client.db("myDB").collection("user").find({}).toArray();
    await client.close();
    return results;
});

What would you advice me to obtain a Stream instead of a Future, using maybe watch collection and Stream change from MongoDB, providing example if possible !

Thank you very much !

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807

1 Answers1

0

Cloud Functions are meant for short-lived operations, not for long-term listeners. It is not possible to create long-lived connections from Cloud Functions, neither to other services (such as you're trying to do to MongoDB here) nor from Cloud Functions back to the calling client.

Also see:

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
  • Would you advise me to look at https://pub.dev/packages/flutter_mongodb_realm otherwise ? I thought it was a better option to handle watch from backend, but if it is not possible, maybe the client could handle it ? Have you ever tried this package ? – David Bernadet Dec 13 '22 at 22:15
  • You may well be able to handle monitoring of MongoDB from your own backend server, but not from Cloud Functions. I usually listen to updates to Cloud Firestore or the Firebase's Realtime Database directly from within my apps. – Frank van Puffelen Dec 14 '22 at 01:33
  • Oh ok thanks ! Just for information if someone is reading this, I tried another package called mongo_dart (https://pub.dev/packages/mongo_dart). At first I thought it was only handly simple CRUD operations, but as I was reading more closely it is in fact offering the command "watch" which is exactly what I was looking for. The only thing is that it's the client which handle the stream and connection to database, not sure if it is or not a good practice... (I'm a newbie in mobile dev) – David Bernadet Dec 15 '22 at 21:30