Firebase Document Fields are getting Deleted - firebase

For some time now, I have noticed that the fields of some of my firebase documents get deleted, even though I do not delete them or write any logic on my app to delete fields of a document or a document itself. This is a picture that shows a document on my firebase project, which has its fields deleted on its own.
The firebase project is connected to my flutter app, but I have not written any delete functionality.
I only update the fields occasionally with recent data.
Please, who has any idea of what's happening?
Edit
This is how I update the documents of my user collections
Future<String?> submitUpdate(User user) async{
CollectionReference userCollection = firestore.collection('users');
String? uid = await secureStorage.read(key: 'uid');
try{
//updates user doc in users collection
await userCollection.doc(uid).update(user.toMap());
return "Success";
}catch(e){
return null;
}
This is how i create the user document in the users collection.
Future<String?> saveUserCredentials(User user) async{
CollectionReference users = firestore.collection('users');
String? uid = await FlutterSecureStorage().read(key: "uid");
try{
//creates a user doc in the users collection
await users.doc(uid).set(
user.toMap()
);
return "Success";
}catch (e){
print(e);
return null;
}
I have a User model that defines the user object.

If you want to set some fields of a document, but keep existing fields, use set with SetOptions(merge: true):
FirebaseFirestore.instance
.collection(...)
.doc(...)
.set({'field1': value1, 'field2': value2}, SetOptions(merge: true));
Without this, the existing fields that are not listed in set will be not be kept, probably this happened to you.

Related

search firebase document for a specific field in flutter dart and store it

im trying to restore a document that its field "email" equal to certain value my code didnt get me anything dont know what is the problem
void EditDisplayedName(String email, String name) async {
CollectionReference s = FirebaseFirestore.instance
.collection("Users")
.doc("list_instructors")
.collection("Instructor")
..where("Email", isEqualTo: email);
s.doc(email).update({'Full Name': name});
} //end method
Your code doesn't yet find/read the document for the email address.
The correct process is:
// 1. Create a reference to the collection
CollectionReference s = FirebaseFirestore.instance
.collection("Users")
.doc("list_instructors")
.collection("Instructor")
// 2. Create a query for the user with the given email address
Query query = s.where("Email", isEqualTo: email);
// 3. Execute the query to get the documents
QuerySnapshot querySnapshot = await query.get();
// 4. Loop over the resulting document(s), since there may be multiple
querySnapshot.docs.forEach((doc) {
// 5. Update the 'Full Name' field in this document
doc.reference.update({'Full Name': name});
});

Flutter - Deleting a document in Firestore leads to the deletion of a random document and not the selected one

The 'utenti' (users) collection contains a document for each user which in turn contains the 'salvataggi' (saves) collection to save objects within the app.
Each document inside 'salvataggi' (saves) has an automatically generated id containing a series of data (String to be precise).
Documents within 'salvataggi' (saves) can be added by saving objects created from two other collections always in FIrestore.
When, through a button, I want to delete an object from the 'salvataggi' (saves) collection, a random document is deleted and not the one corresponding to the object.
Screenshot of Firestore
Object 1
final CollectionReference _usersRef =
FirebaseFirestore.instance.collection('utenti');
final User _user = FirebaseAuth.instance.currentUser;
//Add
Future _addToSaved() {
return _usersRef.doc(_user.uid).collection('salvataggi').doc().set({
'fonte': elenco.fonte,
'title': elenco.title,
'url': elenco.urlAvv,
'imageEv': elenco.urlAvv,
'p1': elenco.iconaProspettiva1,
'p1url': elenco.urlProspettiva1,
});
}
//Remove
Future _removeFromSaved() async {
CollectionReference userSaved =
_usersRef.doc(_user.uid).collection('salvataggi');
QuerySnapshot querySnap = await userSaved.get();
querySnap.docs[0].reference.delete();
}
Object 2
final CollectionReference _usersRef =
FirebaseFirestore.instance.collection('utenti');
final User _user = FirebaseAuth.instance.currentUser;
//Add
Future _addToSaved() {
return _usersRef.doc(_user.uid).collection('salvataggi').doc().set({
'fonte': widget.single.fonte,
'title': widget.single.title,
'url': widget.single.urlAvv,
'imageEv': widget.single.imageEvAvv,
'lastupdate': widget.single.dataAggiornamento,
'p1': widget.single.iconaProspettiva1,
'p1url': widget.single.urlProspettiva1,
});
}
//Remove
Future _removeFromSaved() async {
CollectionReference userSaved =
_usersRef.doc(_user.uid).collection('salvataggi');
QuerySnapshot querySnap = await userSaved.get();
querySnap.docs[0].reference.delete();
}
What am I doing wrong? Why does this happen?
When the user saves a document try saving the id of that document with it so whenever the user unsaved the document. You can pass the id of that unsaved document to firestore.
It will look something like this
Future _removeFromSaved(String docID) async {
CollectionReference userSaved =
_usersRef.doc(_user.uid).collection('salvataggi');
await userSaved.doc(docID).delete()
}
--UPDATE--
You can save document id by calling the then method after adding the document to firestore and then updating it
Future _addToSaved()async {
await _usersRef.doc(_user.uid).collection('salvataggi').add({
'fonte': widget.single.fonte,
'title': widget.single.title,
'url': widget.single.urlAvv,
'imageEv': widget.single.imageEvAvv,
'lastupdate': widget.single.dataAggiornamento,
'p1': widget.single.iconaProspettiva1,
'p1url': widget.single.urlProspettiva1,
}).then(docRef=>await _usersRef.doc(_user.uid).collection('salvataggi').doc(docRef.id).update({'id':docRef.id}));
}
querySnap.documents.first.reference.delete();
Use this instead of querySnap.docs[0].reference.delete();

How to copy all documents from one collection to other in Firestore -Flutter?

I am in a situation where when a users makes a payment, his cart products Stored in Firestore collection (CartProducts) should be moved to new collection Called SuccessFullOrders .
So my Basic Question is how to move all documents from one collection to Firestore other Collection in Flutter
I don't Know how to write code for this in flutter.Thanks for your Answers
Here's my Code
void _onPressed()async {
final FirebaseAuth _auth = FirebaseAuth.instance;
FirebaseUser user = await _auth.currentUser();
print(user.uid);
firestorInstance.collection("users").getDocuments().then((querySnapshot) {
querySnapshot.documents.forEach((result) {
firestorInstance.collection("users").document(user.uid).collection("CartProducts").getDocuments().then((querySnapshot) {
querySnapshot.documents.forEach((result) {
//what to write here so that new documents would be created in other collection
print(result.data);
});
});
});
});
}
Currently there's no way to copy a collection into another provided by firebase officially. And, for sure, you can iterate over your previous collection & create new documents in the other.
In your case you should be doing something like:
userFirebaseInstance
.collection(NewCollection)
.document()
.setData(YourDataHere)

How to delete a subcollection from firestore flutter

so am new using firestore to store data. at the moment i need to delete data already saved in the Firestore through my App. I have tried
Future<void> removeDocument(String id, String userId){
return ref.document(userId).collection(userId).document(id).delete().whenComplete((){
print("DELETE DONE::");
});
}
But its not working.
The thing is I used the userId to save the user details
now I want to delete the data but it does not delete the data even though the print message shows in my Log.
The method below is how i add data to the Firestore
Future<void> addDocument(Map data, String userId){
return ref.document(userId).collection(userId).add(data);
}
void setupLocatorWorkout() {
locatorWorkout.registerLazySingleton(() => Api('workout_goal'));
locatorWorkout.registerLazySingleton(() => CRUDRemoteDataSource());
}
Api(this.path){
print("$path");
ref = _db.collection(path); // this is the base collection
}
please what am i doing wrong here?
Thank you!!!
Delete a User by UID:
void deleteUser(User user) async {
await db.collection(COLLECTION_NAME)
.document(user.uid)
.delete()
.then((_) {
print('User deleted.');
});
}
Don't forget to add import 'dart:async'; at the top
The answer is you shouldn't.
According to the Firestore docs, you should not do this because:
While it is possible to delete a collection from a mobile/web client, doing so has negative security and performance implications.
However the link shows how it can be done frome some platforms.

How to create a custom document in collection - Firestore with Flutter

I sign in my user through google, after successfully login. I wants to create document for each user inside user_details collection and the document name should be google id. But its auto generating document name.
Is there any way to create custom document in Firestore?
Thanks in Advance
// Store data in Firestore
storeData(User user) async {
DocumentReference documentRef =
Firestore.instance.collection("user_details").document(user.id);
Firestore.instance.runTransaction((transaction) async {
await transaction.set(documentRef, user.toJson());
print("instance created");
_login.add(Result(Status.SUCCESS, "Login successful.", user));
});
}
Try this await documentRef.setData(user.toJson());

Resources