How to take the data of a specific column in firebase? - firebase

I'm trying to get the data of the column name. I have the table users and inside it has the columns name, email and phone_number
The code below is what I used to take the table users and the key or the id of the row. This is almost identical to the delete code where I use ref('users/'+key).remove() for that matter
async print(key) {
console.log(firebase.database().ref('users/'+key))
}
I expect the output of name for example 'John'

What you are getting is the reference.
You need to do .once('value') to get a snapshot at that reference, then do .val() on that snapshot to get the data
async print(key)
{
const name = await firebase.database().ref('users/'+key).once('value')
console.log(name.val()))
}

Related

Firestore : Update only a key-val pair

We have a firestore collection, where each document has only one field names.
names contains a map.
Now if, I just want to update a single key value pair in that map, is there a way, other than:
await FirebaseFirestore.instance
.collection(namesCollectionName)
.doc(docId)
.update(savedNames.toJson())
.whenComplete(() => {developer.log("Update saved names success")})
.catchError((error) {
developer.log("Update saved names failed: $error");
throw Exception("Update saved names failed: $error");
});
This code updates the entire map.
I am not sure if there is a way to update just a key value pair. I felt it would be more efficient!
Firestore processes each entries in the map you pass as a set operation on that field.
If you want to update nested fields use . notation to mark that field. So say you store the full name for each user keyed on the Stack Overflow ID as a map under the names field, that'd be:
users
.doc('ABC123')
.update({'names.13076945': 'Nithin Sai'})
If your names field is an array and you want to add a certain name if it doesn't exist in there yet, that'd be an array-union, which looks like this:
users
.doc('ABC123')
.update({'names': FieldValue.arrayUnion(['Nithin Sai'])});

Flutter Firebase firestore append data with unique ID

I'm working on the Flutter app where users can save multiple addresses. Previously I used a real-time database and it was easier for me to push data in any child with a unique Id but for some reason, I changed to Firestore and the same thing want to achieve with firestore. So, I generated UUID to create unique ID to append to user_address
This is how I want
and user_address looks like this
And this is how it's getting saved in firestore
So my question Is how I append data with unique id do I have to create a collection inside users field or the above is possible?
Below is my code I tried to set and update even user FieldValue.arrayUnion(userServiceAddress) but not getting the desired result
var uuid = Uuid();
var fireStoreUserRef =
await FirebaseFirestore.instance.collection('users').doc(id);
Map locationMap = {
'latitude': myPosition.latitude,
'longitude': myPosition.longitude,
};
var userServiceAddress = <String, dynamic>{
uuid.v4(): {
'complete_address': completedAddressController.text,
'floor_option': floorController.text,
'how_to_reach': howtoreachController.text,
'location_type': locationTag,
'saved_date': DateTime.now().toString(),
'user_geo_location': locationMap,
'placeId': addressId
}
};
await fireStoreUserRef.update({'user_address': userServiceAddress});
If I use set and update then whole data is replaced with new value it's not appending, so creating a collection is the only solution here and If I create a collection then is there any issue I'll face?
You won't have any issues per se by storing addresses in a separate collection with a one-to-many relationship, but depending on your usage, you may see much higher read/write requests with this approach. This can make exceeding your budget far more likely.
Fortunately, Firestore allows updating fields in nested objects via dot notation. Try this:
var userServiceAddress = {
'complete_address': completedAddressController.text,
'floor_option': floorController.text,
'how_to_reach': howtoreachController.text,
'location_type': locationTag,
'saved_date': DateTime.now().toString(),
'user_geo_location': locationMap,
'placeId': addressId
};
await fireStoreUserRef.update({'user_address.${uuid.v4()}': userServiceAddress});

How to fetch data from firestore documents from a collection and store in the list

I have a list of a document ids and I want to fetch the data of those documents from Firestore and display it using the FutureBuilder.
contestList = [awebnmsdfjkeeer23,324cdas4asdf, 34sdfasgadsg]
Future<void> fetchUsergameData() async {
contestList.forEach((element) async{
await Firestore.instance.collection('LiveGames').document('$element')
.get().then((dss) {
if(dss.exists) {
tempgame.add(dss.data["GameData"]);
temproom.add(dss.data["Room"]);
temptitle.add(dss.data["Title"]);
temp = tempgame + temproom + temptitle;
joinedContests.add(temp);
}
}).then((value) => {});
});
print(joinedContests);
}
}
I have used the above function to get the data and try to store in the list, like one document data in list. But i am getting the blank list of the data. How to get the whole document and display it using the FutureBuilder in flutter
It looks like you have multiple different issues on your code:
contestList has invalid keywords. 324cdas4asdf and 34sdfasgadsg are not valid variable names as they both start with a number, which is not a valid variable name. If they are supposed to be the ids that you want to retrieve they must be enclosed by ", which will make them strings.
You are trying to access the document using '$element' as if it were a bash variable, but there are two problems there: it's not done like that and there no need to do it. element already holds the value as a string so it just has to be accessed as is.
You are calling the method then twice without doing anything the second time. This shouldn't be a concern, but it simply doesn't do anything and can me omitted.
Below you will see an edited version of your code fixing all the aforementioned mistakes.
contestList = ["awebnmsdfjkeeer23", "324cdas4asdf", "34sdfasgadsg"]
Future<void> fetchUsergameData() async {
contestList.forEach((element) async{
await Firestore.instance.collection('LiveGames').document(element)
.get().then((dss) {
if(dss.exists) {
tempgame.add(dss.data["GameData"]);
temproom.add(dss.data["Room"]);
temptitle.add(dss.data["Title"]);
temp = tempgame + temproom + temptitle;
joinedContests.add(temp);
}
});
});
print(joinedContests);
}
}
On another note, it's unknown to us the type of tempgame, temproom and temptitle but judging by how you are accessing it you may simply want to do something like this:
tempgame = dss.data["GameData"];
temproom = dss.data["Room"];
temptitle = dss.data["Title"];
temp = tempgame + temproom + temptitle;
joinedContests.add(temp);

How to retrieve a document in Firebase using just the id

I have not been able to find a reference in the documentation on how to get a document reference when you know the id of it in firebase.
I am passing the id to a webpage to lookup a QR code. Rather than storing a secondary unique id for each qrcode document I am relying on the firebase unique id.
Here is the lookup I tried but which seems to fail.
firebase.firestore().collection('cues').doc(id).get().then(function (docsnapshot) {
console.info('About: ' + docsnapshot.get('text'));
});
I was able to get my original code to work with this modification to the query
firebase.firestore().collection('cues').doc(id).get().then((doc) => {
... and then just use doc.get("field") to get values form my document
you can access to data like this:
const { id } = docsnapshot
const data = docsnapshot.data()
const myDoc = { id, ...data }
myDoc.text
myDoc.anything...

Search by key, order by value

Here is a sample of my Firebase data:
I need to be able to search userFavorites for a given user (here, afaapy...) and return the results ordered by the values (timestamps) to get all the user's favorites in order of the date added to the database.
I can search by key as follows, and retrieve all favorites for the given user:
databaseRef.child("userFavorites").queryOrderedByKey().queryEqual(toValue: user.uid).observe(...)
But these favorties are ordered by their keys. If I try to order by value as follows, I get "Cannot use multiple queryOrderedBy calls!":
databaseRef.child("userFavorites").queryOrderedByKey().queryEqual(toValue: user.uid).queryOrderedByValue().observe(...)
How can I retrieve the favorites for a given user sorted by their value?
Second question: is there an easier way to retrieve data in the order it was added to the database?
You can't order the same ref multiple times as documented here
When you use a order or a filter method, it returns a Query Interface. See it as a filtered reference containing only a subset of the original data. It means that
databaseRef.child("userFavorites").orderByKey().equalTo(user.uid)
will not return userFavorite/${user.uid} but userFavorite filtered to show only the user.uid entry. You can see it by doing
databaseRef.child("userFavorites").orderByKey().equalTo(user.uid).ref.key
That should return 'userFavorites'
In your case, I see two options:
Keep going with orderByKey().equalTo() and sort the results yourself
Or use directly child() to get the user, then sort via Firebase (and don't forget to use the Firebase's snapshot.forEach to be sure you get the data in the query order):
databaseRef.child(`userFavorites/${user.uid}`).orderByValue().once('value', (snapshot) => {
if (snapshot.exists()) {
snapshot.forEach((child) => {
console.log(`${child.key}: ${child.val()}`)
})
}
})

Resources