firebase firestore get object/array from document - js - javascript

My firestore database currently looks like this:
firestore db
how can I get the value of, say, DEVICES/ID.
currently my code returns undefined when i try to get the value.
var userDeviceRef = db.collection("USERS").doc(data.uid);
userDeviceRef.get().then(function(doc){
if (doc.exists) {
console.log("Document data:", doc.data());
console.log("document customdata foo: " + doc.data().DEVICES.ID);
}
}
data.uid returns a proper value. the value of the document ID.
doc.data() returns all the fields and its children in what appears to be string format. however when I add DEVICES.ID, it returns undefined. how can i get the nested data as shown in the image?

Your field called DEVICES is actually an array. As far as I can tell, it has at least one element in it. If you want the value of the ID field of the first element of that array, you'll have to index into that array:
doc.data().DEVICES[0].ID

Related

How to query an array on a db firestore?

I don't think I'm very far from the answer, I tried to query an id inside an array on Firestore.
I wanna compare the id of the participants.
Also my DB in Firestore:
And also my function, for the moment my function return size =0 so they can't catch the query.
const deleteAbuse = (type) => {
const participants = channel?.otherParticipants;
if (!participants || participants.length != 1) {
return;
}
const myID = currentUser.id;
const otherUserID = participants[0].id;
console.log('id user', otherUserID);
channelDB
.where('participants.id', '==', otherUserID)
.get()
.then((querySnapshot) => {
console.log(querySnapshot.size);
querySnapshot.forEach((doc) => {
console.log(doc.ref);
//doc.ref.delete();
});
});
};
There is no way you can query filter your "channels" collection to get documents based only on a single field of an object that exists inside the participants array. In other words, you cannot create that filtering based only on that ID. To be able to filter the data, you should pass to the where() function, the entire object, and not only some partial data. The object should contain values for all the fields. Only the ID is not enough.
And also my function, for the moment my function return size =0
That's the expected behavior since in your array there isn't any object that holds only a single field called id. All objects hold 7 fields, or even more than that, as I cannot see all fields in your screenshot.
I wrote an article called:
How to update an array of objects in Firestore?
Where you can find in the first part, the simplest way to get a custom object from an array of custom objects.
Alternatively, you can create an array that can hold only the IDs of the participants, filter the documents and create another database call to get their corresponding data.

Trouble calling specific field in Firebase based on the paramater in the URL

I am trying to call the relevent data from Firebase based on the paramater in the URL.
For example:
var userId = 'EqBOy1RVZacBCaNlzbG9NDHrXl23'
//sets the variable to the exercise name in the url
var exerciseName = this.$route.params.exercise_name //'dumbbell_extension'for example
db.collection('track').doc(userId).get().then((doc) => {
if (doc.exists) {
this.exerciseData = doc.data().exerciseName //Returns 'undefined'
}
})
Here is a picture of the database:
Firebase Document Image
This returns undefined despite of the data existing in Firebase and everything else working as intended. I presume this is because it is actually searching for a field called exerciseName instead of the variable exerciseName.
The data() method of a DocumentSnapshot "retrieves all fields in the document as an Object".
You should therefore use the square bracket notation, which allows you to access the Object properties by name, as follows:
var userId = 'EqBOy1RVZacBCaNlzbG9NDHrXl23'
//sets the variable to the exercise name in the url
var exerciseName = this.$route.params.exercise_name //'dumbbell_extension'for example
db.collection('track').doc(userId).get().then((doc) => {
if (doc.exists) {
this.exerciseData = doc.data()[exerciseName]
}
})
You may also be interested by this answer https://stackoverflow.com/a/4968460/7015400, which gives more details about the square bracket notation.
Your code is looking for a field called "exerciseName" in the document, but the document has no such field. The only field in your document, as shown in the screenshot, is called "dumbbell_extension", and we can't see what it contains (it could be a list or map).
Since we don't know what your code is expecting to do, there's no much else to be said. Your code needs to use the names of the fields that are present in the document, or check to see if they actually exist before using them.

Firestore where query with parameter not working

I have a query that is not working as I expect it to. I have a collection called 'games' that has a number of documents in it.
Each document has an array called 'hiScores' that consists of the results from that round. I would like to query all games for a specific player for example:
.where('hiScores.playerName', '==', 'David Lamm')
This is not returning anything. I have no problems when querying a top level variable in the document. What have I done wrong?
Database:
db.collection('games')
.where('hiScores.playerName', '==', 'David Lamm')
.get()
.then(function(querySnapshot) {
console.log('Davids games:')
querySnapshot.forEach(function(doc) {
console.log(doc.id, " => ", doc.data());
});
})
.catch(function(error) {
console.log("Error getting documents: ", error);
}
);
The problem is that the hiScores field is an array, not an object. You can tell it's an array because the first immediate element of the array in the screenshot has index 0. You're trying to query hiScores as if it's a single object with a single property called playerName.
Firestore doesn't support querying for object properties within within array fields. If you have an array field, you can only query to find documents where an entire item is present in the array (an arrayContains query).
As pointed out by Doug this is currently not possible in firestore.
You can create a top level array of strings in each game named playerNames[]. Then use the where condition on playerNames with array_contains.

Indexing into mongoose.model for an array is returning undefined

I've created a simple table (document?) in mongoDB.
I'm using Node and Mongoose to connect to it.
In my method, I am calling model.find({}) to retrieve all records and then iterating over them to find one that I want (this is within a loop - I'm thinking it will be more efficient to hit the DB once, and then process in memory to avoid connecting to the database each time).
When I console.log the match, I'm getting the full object printed out. When I print out one property, however, it's listing it as undefined. This property is an array, and it's happening for another property that has an array that I added as a test. What am I missing here?
Here's my code snippet:
Documents.find({}).then(docsData => { // Documents is my model
docs.entries.forEach(entry => { // docs.entries is the collection I want to match to
const match = docsData.find(
doc => doc['dropboxId'] == entry['id']
);
if (match) {
entry['tags'] = match.tags;
console.log('match tags', match.tags); // this prints out undefined
console.log('match', match); // this prints out the object with tags
}
Any ideas?
match is a Mongoose document which is different from normal JS object. I guess you need to do:
entry['tags'] = match.get('tags');

How To Efficiently Extract Certain Information From A POJO

I am working a lot with firebase, and am trying to load certain information from the database. The original data comes from a query, and is returned to me in a POJO. The console prints this when the original data is returned:
-KhQ76OEK_848CkIFhAq: "-JhQ76OEK_848CkIFhAq"
-OhQ76OEK_848CkIFhAq: "-LhQ76OEK_848CkIFhAq"
What I need to do is grab each of the values (-JhQ76OEK_848CkIFhAq and -LhQ76OEK_848CkIFhAq) separately, and query the real-time database again for each one. I can manage that aspect, but I cannot seem to figure out how to separate the values.
I have already tried to get a single output by doing:
console.log(vals[0]) but it just returned undefined, and splitting the string by " would be very inefficient for large data sets. Any ideas?
To access the values, you can iterate the snapshot's children using the snapshot's forEach method. The keys and values of the children can be obtained using the key property and the val() method:
firebase.database()
.ref("some/path")
.once("value")
.then((snapshot) => {
snapshot.forEach((childSnapshot) => {
console.log(childSnapshot.key); // The child's key: e.g. "-KhQ76OEK_848CkIFhAq"
console.log(childSnapshot.val()); // The child's value: e.g. "-JhQ76OEK_848CkIFhAq"
});
});
To solve this issue, all I did was convert the object returned into an array by using this code below:
var Array = Object.keys(datalist).map(function(k) { return datalist[k] });
Works like a charm, and I can now run a simple for loop for Array

Categories

Resources