Home > Enterprise >  What is the way to update or insert a record on Firebase with Flutter?
What is the way to update or insert a record on Firebase with Flutter?

Time:01-05

I have a collection users like this:

[{
  'uid' : '1',
  'favourites' : [
    { // fav1 },
    { // fav2 },
    { // fav3 },
    etc
  ]
},
{
  'uid' : '2',
  'favourites' : [
    { // fav1 },
    { // fav2 },
    { // fav3 },
    etc
  ]
},
etc
]

In some situations I have to update the favourites collection with a new "fav" and I can do that in this way:

final doc = FirebaseFirestore.instance.collection('users').doc(userId);                      
doc.update({ 'favourites': FieldValue.arrayUnion([fav.toJson()]) });

however the item might be not there so I have to use doc.set to create a new item. As I am new with Firebase, what is a "best practice" for a problem like this (if the element is not there create it first, otherwise update it)?

CodePudding user response:

You can specify a merge option to set, which does precisely what you want:

doc.set({ 'favourites': FieldValue.arrayUnion([fav.toJson()]) }, SetOptions(merge : true))

CodePudding user response:

You can use a function that can check if there is a doc or not with that specific info. And you can create a if-else statement depends on if there is a doc named like that or not.

An example function for checking the doc:

Future<bool> checkIfDocExists(String stuffID) async {
      try {
        /// Check If Document Exists
        // Get reference to Firestore collection
        var collectionRef = FirebaseFirestore.instance
            .collection('favorites');

        var doc = await collectionRef.doc(userId).get();
        return doc.exists;
      } catch (e) {
        throw e;
      }
    }
  •  Tags:  
  • Related