CRUD flutter/firestore/firebase - flutter

I am new to coding and what I am trying to achieve is to set up a method that checks the 'MONDAY' collection inside post and if the data exist? the values of the fields get updated otherwise they get created! I have been stuck for a while now and been redirected to different solutions but nothing has worked for me. I appreciate all help
Future<void> createPostMonday(Post post) async{
await postsRef.document(post.authorId).collection('Monday').setData({
'alOne':post.alOne,
'alTwo':post.alTwo,
'alThree':post.alThree,
'alFour':post.alFour,
'alFive':post.alFive,
'alSix':post.alSix,
'beOne':post.beOne,
'beTwo':post.beTwo,
'beThree':post.beThree,
'beFour':post.beFour,
'beFive':post.beFive,
'beSix':post.beSix,
'likes': post.likes,
'authorId': post.authorId,
'timestamp': post.timestamp,
});

setData() is used to write the contents of a single document whose ID you already know. It requires that you use a DocumentReference object to locate that document.
If you're trying to add a new document to a collection with a unique random ID, you should use add() method of a CollectionReference.
await postsRef.document(post.authorId).collection('Monday').add(...)

Related

Nested replies in a comment sections - How to add new replies for Firebase Firestore

Right now, to add a reply I have to do this:
final CollectionReference postsRef = FirebaseFirestore.instance
.collection('Media')
.doc("<docNumber>")
.collection("Posts")
.doc(document)
.collection("Replies");
I want there to be a way that I could dynamically add replies collection to a document. Right now, the only way for me to do that is if I do .doc().col().doc().col().doc().col()... etc.
As you see, I would rather only have to give a single path instead of having to add many nested collections for adding the information. Is there a way I can just provide a string path?
You can provide a path like this:
final CollectionReference postsRef = FirebaseFirestore.instance
.collection('Media/${docID}/Posts/${docID2}/Replies')
A CollectionReference has odd and a DocumentReference has even number of path segments. So if you want to point to a document, it'll be:
.doc('Media/${docID}/Posts/${docID2}/Replies/${docID3}')

Flutter get future list data into normal list

I am trying to show a list of items in a DropdownField, which requires a non-future list.
So I am trying to turn my future list (which I get from a database call) into a normal list by iterating over it and adding it to a new, normal, list, like so;
When I print the individual elements of the future list, I get results back.
But afterwards, when I print the new list, it returns as a null value.
Does anyone have any idea as to how I can solve this issue ?
PS: I am NOT interested in a FutureBuilder solution. I know that I can show a future list with a futurebuilder, but this will not fit the solution I am hoping to achieve.
Thanks in advance!
That’s because you’re not waiting for the future to complete. When you do print(newList) the future isn’t completed yet.
You will have to need to await the getAnswers data to archieve what you want.
final answers = await getAnswersList();
for (final answer in answers) {
print(answer.toString());
}
The problem is that you are not initializing newList. You are trying to add items to a null list. Change the fourth line of getAll() to the following:
var newList = List<dynamic>();
You are also not awaiting your firebase call. This means that you will print the array BEFORE you finish your firebase call. You need to make this getAll() method async and await, the firebase call so it doesn't print the null version.

Can't use changeable field in Mongoose Sort

Hello i want to use Mongoose sort but i have a problem when i want to change my sorting with arguments it doesn't work. For example
Users.find().sort({sortBy: 1})
Its not working at all. Whats the problem??
You have 2 problems in your code:
1. You are not specifying what field to sort by:
You forgot to change the sortBy field in your sort object to the wanted field to sort by.
For example, if you want to sort your users by name it will look like:
User.find().sort({name: 1})
2. You are not executing your query
You need to execute the query using the .exec(callback) function.
Your code will look like:
Users.find().sort({sortBy: 1}).exec((err, documents) => {
// Your logic
})
You can also use the await keyword to get your data without a callback function.
const users = await Users.find().sort({sortBy: 1}).exec();
Just note that if you decide to use the await option it needs to be in an async function.

Firestore collections snapshot wont convert to csv

I am trying to convert my firestore collection to csv format so i can email it in the code.
I am doing it the following way:
_sendMail() async{
List tempList = await Firestore.instance
.collection("transactions")
.snapshots()
.toList();
print(tempList.toString());
final res = const ListToCsvConverter().convert(tempList);
print(res.toString());
}
The async function never prints the templist and res so im assuming it gets stuck at collection retrieving part.
I know the firestore collection works because i retrieve documents from it in other parts of the app.
I am using the csv package for converting to csv format which requires a list: https://pub.dev/packages/csv
Does anyone know if im doing it wrong or theres another way to do it?
It's not stuck, even if it's offline, Firestore has offline mode and won't wait for anything. Probably tempList is empty, which is why you don't see anything printed.

Flutter Firestore getting incomplete array

I'm trying to fetch an array of strings I have saved on my database but I'm getting the array back with missing values, only the first value is shown inside of it. Here's the structure of my database:
Path: /users/uid/services <-- this is the array
Path: /services/uid <--service document
The code I'm using to retrieve the users is:
_getWorkers() async {
var query = await Firestore.instance.collection('users').where('services', arrayContains: widget.category['uid']).getDocuments();
query.documents.forEach((doc) {
workers.add(doc.data);
List<String> values = List.from(doc.data['services']);
print('services:' + values.toString());
});
var test = await Firestore.instance.collection('users').document('PtBD2EMSTodvlx6WHUx8QOHHLNA2').get();
print('actual services:' + test['services'].toString());
}
Both query and test get data back, but the services array only contains the first value.
Its difficult to answer without actually seeing the entire DB structure. But still on the outset i can see only one error with your code.
When you are trying to execute the where() call, try adding the snapshots to retrieve all relevant data.
Since await is also used, it is much better to call the listen() on it and then read the values to be added to the worker
Try using this below code in place of your first line.
await Firestore.instance.collection('users').where('services', arrayContains: widget.category['uid']).snapshots().listen((query)=>query.documents.forEach((doc)=>print(doc.data['services'])));
For some reason Firebase wasn't returning the updated array. Tested it again today and it worked with the same code. Sorry for bothering, thanks for the help anyways.