Unable to get document data in firestore - javascript

I'm trying to access data from a firestore document, but I'm getting an error message that exercise.data() is not a function. I don't understand how the exercisesToAdd array is an array of documents, but I can't use .data() to get the contents of the items? How else would I go about getting the data from those documents?
I know the exercisesToAdd array is actually being filled with documents because I see them in the database when I send the array. Seems straight-forward but I must be missing something.
chosenExercises.forEach((exercise) => {
exercisesToAdd.push(doc(db, 'Users/' + auth.currentUser.uid + '/Exercises/' + exercise));
});
exercisesToAdd.forEach((exercise) => {
console.log(exercise.data());
});

As #Doug Stevenson stated in his comment:
Your code hasn't actually performed any queries, so there is no document data available. Please review the documentation and use get() to execute each document query first before calling data() on anything. All doc() does is create a DocumentReference, which doesn't contain any data.

Related

Retrieve data from multiple documents from Firestore

I tried a lot of times but I am still not able to retrieve data from multiple documents, The below screenshot shows that I have 3 documents in my collection and my question is how to retrieve data from each of them.
I used foreach loop to loop through all the documents but I don't know how to retrieve data from id RoKQBRcuaVfcGPKNswbx or id Y8KbSQHcuxctJCJ1lWYH because it auto retrieve the data of the last id.
I really need your help, please.
Thank you.
The snapshot object contains all the 3 documents in your collection. You must iterate over all and render data to your HTML as explained below.
db.collection("Policies List").get().then((snapshot) => {
const documents = snapshot.docs //array of documents
documents.forEach((doc) => {
const docData = doc.data() //Data of that single document
console.log(docData)
renderToHtml() // Code that creates new HTML elements
})
})
This way you are creating new HTML elements for all the documents in your collection. The renderToHtml() function will contain that .innerHTML code.
Please make sure to see the logs in the console. They'll help understand the structure in a better way.

How to read last message node in firebase for js app?

I want to read last message node as shown in image below.
I am using below query to retrieve last message where suid and ids are known(as shown in img). but not working.
firebase.database().ref("Messages/"+suid).child(ids+"/chat").orderByKey().limitToLast(1);
How to retrieve last message from firebase realtime db and display it to my console? Thanks
Your existing code looks fine, so let's store that query in a variable first:
const query = firebase.database().ref("Messages/"+suid).child(ids+"/chat").orderByKey().limitToLast(1);
Now you can read the message(s) this query matches with either once() or get(). I'll use once(), since it's much older and hence you're more likely to find examples of it elsewhere:
query.once("value").then((snapshot) => {
snapshot.forEach((message) => {
console.log(message.val().message.msg);
});
})
Some things to note here:
Since a query may have multiple results, the snapshot contains a list of those results. Even if there's only a single result (like here), the snapshot is a list of one result. To loop over these results, we use snapshot.forEach().
Your msg is nested under message in each child, so we use message.val().message.msg to get at its value.

More direct method for updating fields in Firebase document without document ID?

The goal is to update a Firebase document.
The document ID is unknown at the time of updating. What is known is a property that acts as unique key on the document (email address in the case below).
Based on the official documentation and this answer, the code below works as a method for updating an array within the document.
This feels clunky, though.
Are there more direct methods for retrieving a reference to a single document and updating its fields?
// Set query.
let query = firebase.firestore().collection('users').where('emailAddress', '==', 'test#test.com');
// Run query.
try {
const querySnapshot = await query.get();
return querySnapshot.docs[0].ref.update({
designs: firebase.firestore.FieldValue.arrayUnion('foobar')
})
} catch(e) {
console.log('Error getting user: ', e);
}
No, what you're doing is the best you can do. If you don't know the ID, you have to query to find it. Firestore has no equivalent of a SQL "update where" command.

Firestore data modeling and angularFire

I have data model like this
Players-->root collection
Sports--->root collection
Players_Sports---root collection
I want get all the sports(Multiple sport) details or document player belongs.
For this I am using angularFireStore5
First, I am getting
Player details like this
this.db.collection('players').doc(id).get().toPromise()
Second, I am getting Player(user) linked PlayerSport
db.collection<any>('PlayerSports',ref => ref.where('playerId', '==', id) ).get().toPromise()
Third, I am trying to get Sports details based on ID'S,
db.collection<any>('sportsType', ref => ref.where('sportsType' 'in' [sportsIDs])).get().toPromise()
where SportIDs is arrary of ID that are linked in player_sports
First and Second steps works fine, but third steps is not giving any data or response
Could you please let me know where is the problem,
is it in Data model or code? my guess is that data model is not correct. Please guide me on this.
I would suggest getting the data from firebase and storing it inside a list so the app can access it later.
void getDataF(){
databaseReference
.collection("TableName")
.getDocuments()
.then((QuerySnapshot snapshot) {
snapshot.documents.forEach((f) {
iDFacList.add(f.documentID);
dbFacList.add(f.data["FieldName"]);
});
});
}
There is no sportsType field in the sportsType document as far as I can see.
If you're trying to find documents based on their SportsId field, you'll want ref.where('SportsId'....
Update
It seems that you're trying to find a document by its ID, which you can do with:
ref.doc(sportsIDs)
If you want to get multiple documents, or get a single document as a collection, you can use:
ref.where(firebase.firestore.FieldPath.documentId() 'in' [sportsIDs])

JavaScript Firebase: Query Snapshot Always Null

No matter what I do I can't seem to figure out a way to access the child "onSite", which shows as being there when I log snapshot.val(), but I cannot figure out how to access it.
Code:
firebase.database().ref().child("users").orderByChild('facebook_id').equalTo(fbID).once("value").then(function(snapshot) {
console.log(snapshot.val());
console.log(snapshot.child("onSite").val());
});
Here is the response:
It shouldn't be null, it should be false. I can't do child("4mUUjF...").child("onSite").val() because I don't know what the ID is before the query. Using an each loop doesn't work, it only loops through the first level, which is the ID.
Use the key of the object
Get the snapshot val and then find the key with the Object.keys method. This will allow you to then get inside the snap. Once there it's a simple matter of accessing the values like any other object.
firebase.database().ref().child("users").orderByChild('facebook_id').equalTo(fbID).once("value").then(function(snapshot) {
let snap = snapshot.val();
let key = Object.keys(snap)[0]
console.log(snap[key].onSite);
})
When you execute a query against the Firebase Database, there will potentially be multiple results. So the snapshot contains a list of those results. Even if there is only a single result, the snapshot will contain a list of one result.
Your code needs to handle the list, by using Snapshot.forEach():
firebase.database().ref().child("users").orderByChild('facebook_id').equalTo(fbID)
.once("value").then(function(result) {
result.forEach(function(snapshot) {
console.log(snapshot.val());
console.log(snapshot.child("onSite").val());
});
});

Categories