How to query an array on a db firestore? - javascript

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.

Related

Query specific uid in Firebase using Angular2+

Im really confused on how to query a single record in firebase by the uid.
I have a user id and want to query the following table. I am using the following code.
However, it is returning both the records instead of just the 'this.selectedId' one. Is there 1) A way to just return the record being queried 2) keep the key instead of array of index 0, 1, 2, 3 etc...
Code used
const itemsRef = this.afs.collection<any>(`/profiles/`);
itemsRef.valueChanges(this.selectedId).subscribe(
x => {
console.log("Value change", x);
}
);
Image
Returned result
The valueChanges method doesn't take any parameters. If you want to monitor a single document
const itemRef = this.afs.doc<any>(`/profiles/`+this.selectedId);
itemRef.valueChanges()...

Access the second item in Collection [Map]

I'm making a discord bot, and fetching some messages. I got this object
//This parameters changue every time i fetch
Collection(3) [Map] {
'848689862764789770' => Message {...
}
'848689552410804234' => Message {...
}
'848689534485004319' => Message {...
}
I can access the first and third entry using .first() and .last().
I've been trying to use Object.keys() but it returns undefined.
const mensajes = await message.channel.messages.fetch({ limit: 3 });
console.log(mensajes[Object.keys(mensajes)[1]])
Tip:
.first() can take a parameter that will return the first x amount of entries you choose and will then convert the Collection into an Array. Do .first(2) - this will return the first 2 entries - and then access the 2nd element as you would with any other Array.
// Will return 2nd entry
<Collection>.first(2)[1]
Suggested Solution:
You can also call .array() on the Collection to directly convert it into an Array.
// Also returns 2nd entry
<Collection>.array()[1]
<Collection> is a placeholder for your actual object
Learn more about working with Collections in This Guide
DiscordJS's docs has some information on this. You can transform this Collection utility class intro an array with a bunch of methods that exist for it, depending on what you need to access.
Then you can use the array, for example, to access the specific value.
// For values. Array.from(collection.values());
// For keys. Array.from(collection.keys());
// For [key, value] pairs. Array.from(collection);

How to loop through immutable and push it to array Javascript

I have my form field values in an immutable object.
I use getIn immutable function to access it.
For example, if I have to access field, i use const users = formFields.getIn(['0', value]).
Now, i have a variable
users = 4`
This means, there will be 4 fields in immutable from which i need to pick up the users age.
e.g.
1st user age will be stored in formFields.getIn(['1', value])
2nd user age will be stored in formFields.getIn(['2', value])
and so on
How do i loop through the user age list based on the users variable?
I tried something like this:
const userAgeList = [];
if (users >0) {
userAgeList.push(formFields.getIn([[i], value]));
}
With above code formFields.getIn([[i], value]), i get undefined because the value is not actually on this. its on formFields.getIn(['i', value]).
How do i pass the loop variable i as a string so i can get the field values?
If what you have is a List containing Map objects, you can use a map to loop all the values:
const userAgeList = formFields
.map(field -> field.get('value'))
.toArray()
This will give you an array of the values you need.
If you want to take only at a specific i, convert it to a number and then you can combine skip and take in this fashion:
const userAgeList = formFields
.skip(i)
.take(1)
.map(field -> field.get('value'))
.toArray()
This will return you a one element array at the i position.

array-contains not fetching result in 2 Dimensional array

I am saving data in a Document like the below image. I want to fetch the records from array notifyArray , ctg where array-contains Burger.
This is the code i am trying :
firebase.firestore().collection(`notifications`)
.where("notifyArray", "array-contains", 'Burger')
.onSnapshot(querySnapshot=> {
querySnapshot.forEach(doc=> {
console.log(doc.data());
console.log("Search result");
var data = Object.assign(doc.data(), {docid : doc.id})
this.goalList1.push(data);
});
console.log(this.goalList1);
});
But it is not returning any result. Ideally it should return 2 records.
The array notifyArray is an array of maps, each map containing two properties. Firestore doesn't support querying of map properties in an array. You can only search for the entire contents of the map, which means you have to know all of the values of all of its fields.
What you can do instead is make a new array that contains only the string values of the food property in the map, then query that array instead.
firebase.firestore()
.collection(`notifications`)
.where("foodArray", "array-contains", 'Burger')
Above, the query is expecting that there is an array of strings called foodArray.

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