How To Efficiently Extract Certain Information From A POJO - javascript

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

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.

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);

React Native Expo with Firebase: DataSnapshot is object not array

I have some simple data that looks like this, stored in a realtime database of firestore by calling update() and adding in an array as paremeter.
The game is generated by creating an array here and setting it in the "participants" field:
generateNewGame(code, name) {
this.database.ref().update({
[code]: { participants: [name] },
});
}
Now it is time to read the data, this is done by this method setting up a listener:
function setupRegisteredUsersListener() {
FirebaseService.getDatabaseReference(
"/" + codeRef.current + "/participants"
).on("value", (snapshot) => {
if (snapshot.val()) {
// setUsers(snapshot.val());
console.log(typeof snapshot.val());
console.log(JSON.stringify(snapshot.val(), null, 4));
}
});
}
Even though I stored the data as an array, and it LOOKS like an array, the type is Object. How can I circumvent this behaviour, or do I have to manually convert the object to an array somehow?
The documentation, says the .val() function should be able to convert the DataSnapshot into an array. But apparently that is not the default in my case.
The output from the function looks like this:
So obviously the daya is ALMOST an array, but not quite.
Do I have to manually convert the object to an array somehow?
No, you can directly use the value returned by snapshot.val() as an Array.
Array.isArray(snapshot.val()) will return true.
Also, for example, the following will return 0
console.log(snapshot.val().findIndex((element) => element === 'Hej'));
Or, if you add another element, the following will print the values of the two elements
console.log(snapshot.val()[0]);
console.log(snapshot.val()[1]);

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');

Javascript string/object/array confusion with JSON

I'm having a Laravel backend return some errors via Validator. These errors are passed through a HTTP response made by angular, and returned in JSON format.
The object is structured as seen below:
That name object has a value, which is the actual message that I'm after.
Currently, using loops etc., I can only get the name of the array (name) as a string...
I sometimes get multiple arrays within this error object, and I won't always know their names, so how may I retrieve that 0-index value in each of them, in a loop?
Thanks for any help.
Edit #1
Looping through it like this:
for(var err in res.data.errors){
console.log(Object.err[0][0]);
}
Gives me a Cannot get [0] index of undefined
How about this:
let errors = Object.values(response.data.errors);
// errors is now an array of arrays containing the validation errors
errors.forEach( (errorArray) => {
console.log(errorArray[0]);
} );
Another approach would be using Object.keys() instead of values. This is similar to what you already tried, where you get the name of the error property as a string, and then use it to access each error array:
let keys = Object.keys(response.data.errors);
keys.forEach( (errorKey) => {
console.log('error type', errorKey);
let errorArray = response.data.errors[errorKey];
console.log(errorArray[0]);
} );

Categories

Resources