I use Firebase in my Flutter project. I store a UserID in the array in a document in the Article Collection when someone favorites an article.
In a slide action of a list, I implemented a button that should either show a broken heart or a filled heart, depending on whether a user has already favorited the item or not.
I've already felt like I've scoured the whole internet for a method to see if the UserID of an article is in the array and somehow I'm at a loss.
Here is my Datastructure in Firebase
Although I can access this data via a stream, it only provides me with the articles with the corresponding UserID (which I need for a second page in my project)
Stream<List<Artikel>> readFavArtikel() => FirebaseFirestore.instance
.collection('artikel')
.where('userFavs', arrayContains: (globals.getUserID()))
.snapshots()
.map((snapshot) =>
snapshot.docs.map((doc) => Artikel.fromJson(doc.data())).toList());
I also know that by means of
documentSnapshot.get('userFavs')
can get a list of UserIDs. How can I then implement this in an if query to check whether this list contains a specific UserID
Related
Im trying to retrieve from firebase based on two conditions
`
final medResult = await userMedDB.userMedCollection
.where('userID', isEqualTo: Auth().uID)
.where('name', isEqualTo: medName)
.get();
`
is that code correct??
If you're trying to query google-cloud-firestore (you tagged with firebase-realtime-database, which is a different database) the code is correct.
If your query doesn't work when you add the second condition, you may be missing a composite index that is needed for this query. In that case, can any errors that may happen, log them to the console, and find the link in the error message. This link takes you directly to the Firebase console with all values filled in to create the correct index at the click of a button.
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 days ago.
Improve this question
I have a API that gives me a list of hotels name. I have shown the list of hotels in listView. In the listView , I have created a button for rating the hotels which will be given by the users. It also store's the value of rating together with its index hotel in the Firebase. Now my question is how can I show the stored rating value in the listView from Firebase with respect to it index hotel name?
can anyone help me on this?
can anyone help me on this? or give me any suggestion in this matter. Thanks in advance.
I hope i understand your issue correctly, one way you could match the data from firebase with your api data is as follows:
Let's say that your API returns an id or even just the name of the hotel. You create a list that displays the hotels with their ratings. Initialy the rating will be empty. Every time a user rates a hotel, you update the collection in your Firebase. The first time the collection will be created alongside the document.
Each document must have an id that can be matched with the item that you are storing. (Your api returns a hotel with id '1' or name 'hotel', then the document must have id '1' or id 'hotel' )If a hotel has already been rated by a user, the rating of the document will be updated. In order to match the id/name of the hotels that are being fetched by the API you will need to have an identical id/name passed as the id of the document for each hotel.
If a document exists with the id/name of the hotel you are currenlty searching for then match it in your list.
When starting your application you could fetch your api data run throught all of hotels and for each hotel look at the FireBase for an existing document with matching ID and then format and store both the api and Firebase data in a list/map and use that one to create your listview.
I am trying to make a firebase database call to retrieve all row of one particular column in the firebase database of my app and display it in a textbox in my flutter app.
That is, to retrieve all phone numbers in the Users table.
For instance, in SQL we can do like this:
SELECT (PhoneNumers) FROM Users
I am new in flutter/dart, I need some help.
Its really easy.
First of all, setup and initialize firebase in you project. Then make a function and create an instance of firestore like this
FirebaseFirestore firestore = FirebaseFirestore.instance;
Then make something called Collection reference:
CollectionReference users = await firestore.collection("users").get().then((querySnapshot) {
querySnapshot.docs.forEach((doc) {
print(doc["PhoneNumber"].toString())
});
This will grab every collection from Users, loop over them and then print out the document PhoneNumber to console. There is no way to just get a single document field from firestore. It might seem weird, but its quite useful at times. Right now, you have access to every document field of every user of your app.
I've been trying to implement live messaging in my application and I cannot seem to think of a convenient data structure inside Firestore. My current structure looks like this:
collection("conversations").document(id).collection("messages")
Each document holds two attributes user1 and user2 with nicknames of contributors to the conversation. Each document also owns a collection called messages which holds documents where each represents a single message sent with some info.
What I'm trying to do next is to check if the conversation already exists, if not then create it. The problem for me is write a correct query to find out if it exists.
My first idea was: create users array instead which holds nicknames of users and then simply query:
db.collection("conversations").whereField("users", in: ["username1", "username2"])
Problem with this is that it means "where users contains username1 OR username2", but I need it to contain "username1 AND username2".
I tried to be smart and chain the whereField function as following:
db.collection("conversations").whereField("users", arrayContains: "username1").whereField("users", arrayContains: "username2")
Turns out that you cannot use arrayContains more than once in a single query.
After that I came back to the structure as displayed on the screenshot with user1 and user2 and ran a new query:
db.collection("conversations").whereField("user1", isEqualTo: user).whereField("user2", isEqualTo: friend)
This query is ran in a function where user and friend are string parameters holding nicknames of both sender and receiver of the message we're currently sending. Imagine you are sending a message, user is always going to be your nickname and friend the receiver's one. The problem with the query is that you're nickname might be saved under user1 or user2 and receiver's nickname aswell. In either of those situations the conversation exists. How would I have to change the query since I don't know in an advance who will have which position in the query aswell as in Firestore. Running the last query that I included twice while switching user and friend parameter seems very unconvenient.
Any tips or solutions to progress in this problem will be much appreciated!
I'd like to start using Firebase as my main BaaS now that Parse is closing. At the moment, Firebase's real-time capabilities are interesting and I see using them in the future, but for now I'd primarily like to use Firebase as a way to store a User and there associated data. With Parse, this was super easy, which required only uploading an object with the associated user attached to the object. I could then filter by the objects which were associated with that user.
However, in Firebase everything is Event driven as opposed to on-demand and you can't filter by security rules. In general, I like this approach, but I'm having trouble applying it to what I need today. I don't have much of background in networking/databases, so its possible some of this stuff is really basic.
Here is what I'm looking to do:
My Firebase data structure looks like this currently:
xnterval
users
100b920f-d2c5-4578-9f49-ecf38ef71302
32a8dbf2-009a-44c5-a188-ca2c280ba135
d53b0b37-d773-4cf5-af94-74635fc76f1f
name: "Joe Schmo"
provider: "password"
username: "jschmo"
workouts
-K9wZ4_Rt-xBdVZt93d4
workout_id: "-K9wZ4_Rt-xBdVZt93d3"
workouts
-K9wZ4_Rt-xBdVZt93d3
interval_period: 180
intervals: 2
name: "Workout"
owner: "d53b0b37-d773-4cf5-af94-74635fc76f1f"
rest_period: 150
work_period: 30
Inside the User/"uid" I have a workouts list which is order by childByAutoId and contains the ID of a single workout.
What I want to be able to do, is get a list of all the user's workouts and then retrieve that complete workout list from the workouts section.
I know the PATH directly to the users workouts root/"uid"/workouts, but how would I retrieve the entire list and get each "workout_id" and then subsequently query for that list of workouts in the /workouts section?
I've also already setup Security rules such that no other user can access another users data, and the only user that can read/write a workout is if the owner of that workout is the UID on the authenticated user. This I do have working correctly.
Maybe I'm going about this the wrong way, or there is an easier way to structure my data to accomplish what I want. I read a few articles on de-normalizing your data in order to optimize the amount of transfer required in a query, and building for the future I feel like this data structure is ideal for that. But if you have more experience, please let me know. Thanks!
Update
So I've create this method which will retrieve all the user's workout ID's and store them into an array userWorkoutIds:
private func observeAllUserWorkouts() {
if userAuthData != nil {
workoutObserver = userRef?.childByAppendingPath("workouts").observeEventType(FEventType.Value, withBlock: { snapshot in
let enumerator = snapshot.children
while let child = enumerator.nextObject() as? FDataSnapshot {
NSLog("\(child.childSnapshotForPath("workout_id").value)")
self.userWorkoutIds?.append(child.childSnapshotForPath("workout_id").value as! String)
}
})
}
}
Now that I know exactly the paths of all the users workouts /workouts/"IDs", how can I poll for all of them at once as opposed to setting up single shot observers for all the different paths? OR is that the only option?
A super quick solution: add the uid of the user to the workout_id node.
Then you can query on the workouts node for uid equal to the user of whose workouts you want to retrieve.
workouts
workout_id_0
interval_period: 180
internvals: 2
uid: user_id
workout_id_1
interval_period: 180
internvals: 2
uid: user_id
A second option:
If you know the path to the user workouts
/users/uid_id/workouts
you could observe the node by value, which would read in all of the children in that node into a snapshot. Then iterate over the snapshot to get specific data. I personally would load each item in the snapshot into an array of dictionaries or maybe even workout object.