This question already has answers here:
How to add values to Firebase Firestore without overwriting?
(5 answers)
Why is my Cloud Firestore Transaction not merging when using SetOptions.merge()?
(1 answer)
Closed 4 years ago.
I'm new to Firestore and I am having some trouble even though I have gonne through the docs.
I have the following structure:
buses (collection) -> cb-123-1 (document) -> many custom objects
Now I am trying to add data following the docs:
PassengerModel passengerModel = new PassengerModel(
Integer.parseInt(seatNo.getText().toString()),
"selected");
mFirestore.collection("buses").document(mBusUid)
.set(passengerModel, SetOptions.merge());
Now the item is added alright on click however it replaces whatever exists in my document instead of adding to it.
I assume your PassengerModel class has all properties for the passenger. In that case the behavior is expected: Firestore loops through all properties of the class. If no value is present for a property, that property is deleted.
You're more likely looking to patch, which requires a data model that only has the properties that you want to modify. An easier and more common approach is to use a Map for patches, or this even simpler approach:
mFirestore.collection("buses").update(seatNo, Integer.parseInt(seatNo.getText().toString()))
Related
This question already has answers here:
Flutter how to add map to existing array on firebase
(1 answer)
How can I update map data that's in a array in firebase? (Flutter)
(2 answers)
Flutter Firestore: update array of object by param
(1 answer)
Closed 4 months ago.
I am trying to develop a stock management application on Flutter. I have integrated Firebase into the app and I can view the data on the app. My collection and documents are as follows:
I want to add a new element to an array in an already existing document wtih this.
Map<String, dynamic> urunData = {
'ad': _adController.text,
'kod': _barcodeController.text,
'seri': _seriController.text,
'raflar': [
{'raf': dropdownValue, 'adet': _rafController.text},
],
'sirket': _sirketController.text,
'tarih': FieldValue.serverTimestamp()
};
sayimRef.doc(_barcodeController.text).update(urunData);
But in this way, the other elements in the 'raflar' array inside document are deleted and it is transformed into a new array with one element. How do I update an existing index or add a new one without deleting other elements?
This question already has answers here:
Android: Firebase Search Query not working properly
(2 answers)
Closed 1 year ago.
private void processsearch(String s)
{
FirebaseRecyclerOptions<Calories> options =
new FirebaseRecyclerOptions.Builder<Calories>()
.setQuery(FirebaseDatabase.getInstance().getReference().child("Food").orderByChild("Name").startAt(s).endAt(s+"\uf8ff"), Calories.class)
.build();
adapter=new myadapter(options);
adapter.startListening();
recview.setAdapter(adapter);
}
how can I make this search method case insensitive?
I've tried doing
String n="Name";
n.equalsIgnoreCase()
; then replaced the word name in orderbychild with n but it didn't work
I've also tried toLowerCase on n, I can't seem to find the method .equalsIgnoreCase() inside the recylcerOptions that's why i tried to do it on the outside
When you store your strings in your database, you should use a method to make it all lower case, such as string.toLowerCase().
And when you query, you convert your query to lower case as well query.toLowerCase()
there are other factors to consider such as special characters that should be removed/ignored but that is out of the scope of this question.
Let's say that I have a document like this:
Document {
tags: list<Int> {0,1,2}
}
I want to change it to this:
Document {
tags: list<String> {SEASON, TRAINING, TOURNAMENT}
}
I have active users which uses the list of ints, How do I create a migration in Firestore for this problem?
One solution I have in mind is to make 2 migrations:
For creating a new tags called tagsStrings.
For deleting all users who still have tags.
But can I make it in 1?
I was unable to find documentation for this, on https://cloud.google.com/firestore/docs/manage-data/move-data
Thanks in advance
Firestore does not have a "migration" like SQL databases. The only way to modify data in existing documents, in bulk, is to:
Query for the documents to change
Iterate the results
Update each document with new values
Each one of these tasks should be straightforward.
You might also consider lazily updating each document as each are individually read during the normal course of your app's usage. So, if your app reads a document in the old format, immediately update it to the new format.
It's often helpful to have a dedicated field in each document to indicate which version of data that's contained within. So, initially set v=1 in each document, assign v=2 to mean that the document has strings instead of numbers for tags, then use that number to determine which documents have yet to be migrated.
This question already has answers here:
How to remove child nodes in firebase android?
(4 answers)
Closed 5 years ago.
I use following code to add a child and set a value to it in FireBase.
String ref = Constants.Client+"/"+Constants.firebaseProjects+"/"+Constants.ProjectName+"/xyz";
final DatabaseReference ref = FirebaseDatabase.getInstance().getReference(FirebaseRefer);
ref.child("mockChild").push().setValue("")
What can I do to delete the "mockChild" ?
ref.child("mockChild").removeValue();
Code to add child - ref.child("mockChild").push().setValue("Hello");
Code to remove child - ref.child("mockChild").removeValue();
Lets take an example in a user db:
ref.child("Users").child("User1").setvalue("User 1");
ref.child("Users").child("User2").setvalue("User 2");
ref.child("Users").child("User3").setvalue("User 3");
Now if you want to remove a specific user from the database you have to use this code:
ref.child("Users").child("User2").removeValue();
Since firebase is a key value database, it will remove the value from User2 and also the key since the key can't be on it's own. This will remove the entire reference to User2 from your database.
To solve this, please use the following code:
String key = ref.child("mockChild").push().getKey();
ref.child("mockChild").child(key).setValue("yourValue");
ref.child("mockChild").child(key).removeValue(); // This is how you remove it
or you can use:
ref.child("mockChild").child(key).setValue(null);
It's also accepted and means that when you give Firebase a null value for a property/path, you indicate that you want to property or path to be deleted.
If you want to remove the entire child, then just use:
ref.child("mockChild").removeValue();
Note, it will remove everything that mockChild contains.
This question already has answers here:
Query based on multiple where clauses in Firebase
(8 answers)
Closed 7 years ago.
I'm using firebase on my android app. I need help to find an issue to my trouble. I want to do a request like this: I was using the oderbyChild("date") to oder my data from the nearest date to the farest by doing this.
MyApplication.backend.child(urls).orderByChild("value").addValueEventListener(new ValueEventListener() {
}
now i want to this select all where the activity value is done and order theme by my date value. i have write this :
MyApplication.backend.child(urls).orderByChild("task").equalTo("done").addValueEventListener(new ValueEventListener(){
}
My problem is that it's not possible to do 2 two orderByChild on the same fireBase query. How can i fix this ? please need help.
Assuming your data looks like this
activities
-JKjasjiji
date: 20151129
is_done: false
-Ykkjaso23
date: 20151128
is_done: true
-Jkaisjiij
date: 20151127
is_done: false
There are a few ways to go about this.
1) query for all activities where is_done: true then sort the results in code. This could be very inefficient depending on data set size. Sorting 1 Million in code would be bad.
2) Store the done activities in another node
activities
-JKjasjiji
date: 20151129
-Jkaisjiij
date: 20151127
done_activities
-Ykkjaso23
date: 20151128
3) Store the data in a format that will enable an 'and' type query
activities
-JKjasjiji
done_and_date: false_20151129
-Ykkjaso23
done_and_date: true_20151128
-Jkaisjiij
done_and_date: false_20151127
Then user .startAt and .endAt...
ref.orderByKey().startAt("true_20151128").endAt("true_20151129")
Would give return all activities that are done between the two specified dates.
Structuring your data can simplify your queries.
#Jay's answer is great. Here's another way to crack this nut, with the Bolt compiler.
Let's say you're building an expense reporting app, and your data structure goes as follows:
type User {
name: String;
uid: String;
}
type Expense {
id: String;
amount: Number;
uid: uid;
year: Number;
}
path /users/$uid is User;
path /expenses/$expense_id is Expense;
Now let's say you want to get all of the expenses by user 1 that happened in 2014. If this were SQL you could say:
SELECT *
FROM Expenses
WHERE uid == "1" AND year == 2014
With the Firebase SDK you would like to do something like this:
ref.child('expenses')
.orderByChild('uid')
.equalTo('1')
.orderByChild('year')
.equalTo('2014');
But, that's not possible. So what are we to do? Re-structure our data to fit this kind of query.
Rather than store all the expenses under the /expenses location, we can create an index for year with /expenses/year. This would look like:
path /expenses/$year/$expense_id is Expense
Now the query we wanted to do above can be acheived with:
ref.child('2014')
.orderByChild('uid')
.equalTo('1');
The structure you choose for your data will allow you to get the data as you need. You may find that you need to duplicate your data to do this. This is okay. And if you need to keep your data consistent across multiple locations, you can use client-side fanout.