Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to skip null/empty variables in the firestore collection?

Like firebase real-time database, I don't want store null/empty value in firestore collection .so how i can skip or remove null fields from firestore collection enter image description here

below function save data to firestore

private void saveTofireStore(String path, User userObject,Class<?> classType){

    FirebaseFirestore db = FirebaseFirestore.getInstance();
    documentReference = db.document(path);
    Log.d(TAG,""+documentReference.getPath());
   documentReference
            .set(userObject)
            .addOnCompleteListener(task -> {
                if (task.isSuccessful()){
                  appearanceMutableLiveData.setValue(task.getResult());
                }else {
                    appearanceMutableLiveData.setValue(null);
                }
            });

}
like image 289
Hamza Avatar asked Jul 06 '18 19:07

Hamza


People also ask

What is Subcollection in firebase?

A subcollection is a collection associated with a specific document. Note: You can query across subcollections with the same collection ID by using Collection Group Queries. You can create a subcollection called messages for every room document in your rooms collection: collections_bookmark rooms. class roomA.

How do I get no of documents in firestore?

If you need a count, just use the collection path and prefix it with counters . As this approach uses a single database and document, it is limited to the Firestore constraint of 1 Update per Second for each counter.

How many documents can be stored in a collection firestore?

20 for multi-document reads, transactions, and batched writes. The previous limit of 10 also applies to each operation.


2 Answers

I found an easy way using Gson to serialize object then convert into the map then you can save that object

private Map<String, Object> removeNullValues(User userObject) {
    Gson gson = new GsonBuilder().create();

    Map<String, Object> map = new Gson().fromJson(
            gson.toJson(userObject), new TypeToken<HashMap<String, Object>>() {
            }.getType()
    );

    return map;
}

and then

documentReference
.set( removeNullValues( userObject) )
.addOnSuccessListener {}

If you are using proguard then make sure add this rules

-keepclassmembers enum * { *; }
like image 190
Hamza Avatar answered Nov 04 '22 04:11

Hamza


My solution was to add a method called toFirestoreJson.

import 'package:cloud_firestore/cloud_firestore.dart';

class User {
  String documentID;
  final String name;
  final String city;
  final String postalCode;
  final String state;
  final String address;
  final List<String> emails;

  User(
      {this.name,
      this.city,
      this.postalCode,
      this.state,
      this.address,
      this.emails});

  factory User.fromFirestore(DocumentSnapshot documentSnapshot) {
    User data = User.fromJson(documentSnapshot.data);
    data.documentID = documentSnapshot.documentID;
    return data;
  }

  factory User.fromJson(Map<String, dynamic> json) => User(
        name: json["name"] == null ? null : json["name"],
        city: json["city"] == null ? null : json["city"],
        postalCode: json["postal_code"] == null ? null : json["postal_code"],
        state: json["state"] == null ? null : json["state"],
        address: json["address"] == null ? null : json["address"],
        emails: json["emails"] == null
            ? null
            : List.castFrom(json["emails"]),
      );

  Map<String, dynamic> toFirestoreJson() {
    Map json = toJson();
    json.removeWhere((key, value) => value == null);
    return json;
  }

  Map<String, dynamic> toJson() => {
        "name": name == null ? null : name,
        "city": city == null ? null : city,
        "postal_code": postalCode == null ? null : postalCode,
        "state": state == null ? null : state,
        "address": address == null ? null : address,
        "emails" : emails == null ? null : emails,
      };
}
like image 29
teteArg Avatar answered Nov 04 '22 04:11

teteArg