`Future<void> updateData(bool durum) {
var ref= _firestore
.collection("Person")
.doc(firebaseUser?.uid)
.collection("Kelimeler")
.doc()
.update({
"durum":durum,
},);
return ref;
}`
I wrote a data update function. Since the data is nested in my database, I need to update the innermost data, but if I write it in the doc() part of the code, the text is not accepted.
Related
I have stored my document ID inside a string doc_id. I want to use this doc_id to access the subcollection from another file.
This is how I stored the doc_id :
onPressed: () async {
await FirebaseFirestore.instance
.collection('blogs')
.add({
'postbody': postController.text,
}).then((value) {
doc_id = value.id;
}).catchError((error) => errorAlert(context));
}
I have tried another way, like storing this doc_id as a field value inside the collection 'blog',
await FirebaseFirestore.instance
.collection('blogs')
.doc(docid)
.update({'postid': docid});
But then while fetching the data using get() it needed the documentid for fetching. Is there any way that I can read values without documentid.
Or how can I access this doc_id from another dart file ?
You can read on collection to get all blog, Or run query with it to prevent read too much document one time that can increased costs, like FirebaseFirestore.instance.collection('blogs').limit(10).snapshots()
I have the following code in flutter:
QuerySnapshot querySnapshot =
await _firestore.collection("user1#gmail.com").get();
List Data = querySnapshot.docs.map((doc) => doc.data()).toList();
print("Length: ${Data.length}");
Here is my firestore database:
I get the following output:
I/flutter (11484): Length: 0
The Documents for each user email is variable, so I need the length of the documents. Also I need to get to the details of each document like content and title. How to do it? Thanks.
Could you try this:
int size = await FirebaseFirestore.instance.collection(collectionPath).get(GetOptions(source:Source.server))..size;
I will recommend finding a way to store the length of documents as a field in your Cloud Firestore database because calling the get function on a whole collection means filling up the mobile phone memory. (Say you have 500,000 users at least). This makes your app slow
You could have a field called count such that when you add a document, you can use the firebase transaction to update firebase.
For example:
// Create a reference to the document the transaction will use
DocumentReference documentReference = FirebaseFirestore.instance
.collection('users')
.doc(documentId);
return FirebaseFirestore.instance.runTransaction((transaction) async {
// Get the document
DocumentSnapshot snapshot = await transaction.get(documentReference);
if (!snapshot.exists) {
throw Exception("User does not exist!");
}
// Update the follower count based on the current count
// Note: this could be done without a transaction
// by updating the population using FieldValue.increment()
// Perform an update on the document
transaction.update(documentReference, {'followers': FieldValue.increment(1);});
// Return the new count
return newFollowerCount;
})
.then((value) => print("Follower count updated to $value"))
.catchError((error) => print("Failed to update user followers: $error"));
You can see more documentations here: FlutterFire
Is it possible to write to a Cloud Firestore NEW document subcollection while user is offline?
In my app, the user will add a new document with items being added to the document's subcollection. Everything works fine when the device is online. But when offline, the first level collection document seems to be added as expected, however the subcollection items are not added until the devise is back online.
I understand that Firestore have offline persistence enabled by default and it will write documents to cache if the device loses connectivity. But is it only able to write the documents to the first level collections?
Can I add to the subcollection without awaiting until the new document is written on the server (i.e. use cache reference) since the persistence feature is not working with async/await functions?
Below is my sample code for writing to Cloud Firestore. I am not able to fetch the subcollections until back online - the data from get() will return empty.
Can anyone please help me with this? Apologies if this has been answered somewhere - I couldn’t find it.
void main() async {
await Firebase.initializeApp();
FirebaseFirestore _firestore;
_firestore = FirebaseFirestore.instance;
runApp(
MultiProvider(
providers: [
Provider<MyFirestoreFunctions>(create: (_) => MyFirestoreFunctions(_firestore)),
],
child: MyApp(),
),
);
}
class MyFirestoreFunctions {
MyFirestoreFunctions(this._firestore) : assert(_firestore != null);
final FirebaseFirestore _firestore;
Future<DocumentReference> addNewDocument(DocClass doc, ItemClass item,) {
Future<DocumentReference> result = _firestore
.collection('Documents')
.add(doc.toJson())
.collection(‘Items’) // I cannot do this without await and cannot use await while offline.
.add(item.toJson());
return result;
}
}
I think I figured it out with some help from another answered question on here. Obviously, I was doing it wrong… I changed the code to first generate a new DocumentReference and set its values from the map. This way I don’t have to await for the Future to return and will have the reference of the document to add to its subcollection. Now everything works as expected. Here’s the rewrite to the sample code:
Future<void> addNewDocument(
{#required DocClass doc,
#required ItemClass item}) {
final DocumentReference docRef = _firestore.collection(‘Documents’).doc();
doc.id = docRef.id;
_firestore.collection(‘Documents’).doc(doc.id).set(doc.toJson());
final DocumentReference itemRef = docRef.collection('Items').doc();
item.id = itemRef.id;
docRef
.collection(‘Items’)
.doc(item.id)
.set(item.toJson());
}
I tried with different ways but i can't edit the structure of code
//First way
QuerySnapshot querySnapshot = await db.firestoreInstance.collection('user-history').get();
var list = querySnapshot.docs;
print('MY LIST ===== $list');
//Second way
final CollectionReference collectionRef = db.firestoreInstance
.collection(historyCollection);
print('MY SECOND LIST ===== $list');
collectionRef.get().then((qs) {
qs.docs.forEach((element) {
print('MY doc id ${element.id}');
});
});
In my firebase collection(historyCollection) i have four documents but the debugger returns me empty array []. Is there another way to call all documents in certain collection through flutter?
I'm trying to call this method through FutureBuilder component.
My version of firestore is: "cloud_firestore: ^0.16.0+1"
This should do the trick:
Future<List<dynamic>> getCollection(CollectionReference collection) async {
try {
QuerySnapshot snapshot = await collection.get();
List<dynamic> result = snapshot.docs.map((doc) => doc.data()).toList();
return result;
} catch (error) {
print(error);
return null;
}
}
The entire problem was not from these fragments of code. This problem is came out from this that my collections have subcollections. I read about this and i understand that subcollections can live without their ancestors and the only way to access parents is to do this is directly specify the exact path and name of the document. To work this code in my case was needed to add dummy components of my entire set of collections. For more information please look up these two topics:
-> https://firebase.google.com/docs/firestore/using-console
-> Firestore DB - documents shown in italics
I am trying to figure out how to update my document after I query the one I want to update. Here is the code I came up with:
Firestore.instance.collection("Social_Posts").where(data["postTitle"], isEqualTo: "postTitle").where(data["postContent"], isEqualTo: "postContent")
.snapshots()
.listen((event) {print("hh");});
Whenever I perform this query to find the correct document, I would like to update the document by adding a number to it.
It is possible to update the document from inside, The easier way to do that would definitely be to use the documentID and to increment the value Firestore has a special property, FieldValue.increment(1). Using this you can easily increment a field.
Lets say the field in the document you want to increment by 1, is "numberField".
Updated code using async/await style:
onTap: () async {
setState(() {
_title = data["postTitle"];
_content= data["postContent"];
});
print(_title);
print(_content);
QuerySnaphot snapshot = await Firestore.instance.collection("Social_Posts")
.where("postTitle" , isEqualTo: _title)
.where("postContent", isEqualTo: _content)
.getDocuments();
if(snapshot.documents.isNotEmpty)
{
snapshot.documents.forEach((doc){
doc.reference.updateData({"views" : FieldValue.increment(1),});
});
}
}
The numberField will be incremented without needing to make an extra call to know the present value.
EDIT : You were making a mistake in the .where() method
You can do that by using the document id you quired from inside the listen function in your case by using the event.documents[0].documentID assuming that your query returns one document only and then you can call the updateData method from Firestone package
Your code might looks like this:
Firestore.instance.collection("Social_Posts")
.where(data["postTitle"], isEqualTo: "postTitle")
.where(data["postContent"], isEqualTo: "postContent")
.snapshots()
.listen((event) {
Firestore.instance
.collection("Social_Posts")
.document(
event.documents[0].documentID)
.updateData(
updateEvent) //Add here the new object you want to
.whenComplete(() {
// You can add your desire action after the row is updated
}
});
You can check package page for more information https://pub.dev/packages/cloud_firestore
And if you want to check a sample on how to perform CRUD functionalities you can check this repository: https://github.com/sayed3li97/flutter_firestore_crud