firebase - Get the uniqe push ID - javascript

I want to get the unique ID of push method for this data:
{
"users": {
"-KKUmYgLYREWCnWeHDfT": {
"fName": "Peter",
"ID": "U1EL9SSUQ",
"username": "peter01"
},
"-KKUmYgLYREWCnWeHCvO": {
"fName": "John",
"ID": "U1EL5623",
"username": "john.doe"
}
}
}
Since name() has been deprecated I tried to use .key, but it returned not the unique ID, but the users key instead.
ref.child("users").orderByChild("ID").equalTo("U1EL9SSUQ").once("value", function (snapshot) {
console.log("KEY: " + snapshot.key); // snapshot.key === users
});

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.
By calling snapshot.key you are getting the name of the node on which the query was executed. The deprecated snapshot.name() would have done the exact same thing.
To get the key of the matches item, you need to loop over the snapshot's children:
ref.child("users")
.orderByChild("ID")
.equalTo("U1EL9SSUQ")
.once("value", function (snapshot) {
snapshot.forEach(function(child) {
console.log("KEY: " + child.key);
});
});

You need to use .val() to extract a Javascript value from a DataSnapshot. The following should work.
ref.child("users").orderByChild("ID").equalTo("U1EL9SSUQ").once("value", function (snapshot) {
console.log("KEY: " + Object.keys(snapshot.val())[0]);
});

Related

How to get N index of array from JSON arrays

Hi I have JSON file that have users nickname, password and token. I'm using a find function to find users from their nicknames. I want to get tokens too.
[
{
"user": [
"bombali",
"reYiz_2031",
"GcjSdUMp"
]
},
{
"user": [
"johndoe",
"testpasswd1_s",
"SdNFccRT"
]
}
]
This is my JSON data file.
I'm checking if nicname is taken or not using this code:
function isUsernameTaken(username) {
const user_Database = require(`${config.path_users}`);
const finded_Name = user_Database.find(
({ user }) => user[0] === username.toLowerCase()
);
if (finded_Name === undefined) {
console.log("This username is usable");
} else {
console.log("This username is unusable");
}
}
Now I want to get token from json by using username and password to use filter. I don't want to use token:SdNFccRT in array. Is it possible? Thanks for all replies.
Using .filter() isn't the best choice in this case. With .find(), the search will stop once one element has been found, but .filter() will keep on going when it doesn't have to.
Given the username and password, you can find the token with a single .find() statement that compares each user object's username and password, then returns the token of the match. You can also use optional chaining to return undefined if no match is found. Like this:
const getToken = (data, uname, pass) => data.find(({user}) => user[0] === uname && user[1] === pass)?.user[2];
const data = [{
"user": [
"bombali",
"reYiz_2031",
"GcjSdUMp"
]
},
{
"user": [
"johndoe",
"testpasswd1_s",
"SdNFccRT"
]
}
];
console.log(getToken(data, 'bombali', 'reYiz_2031'));
console.log(getToken(data, 'none', 'none'));

Cloud Functions problem, query resulting in an Array?

I need to get inside of itens to go into some item, than into product to get the "ean" field and
check if some product have the "ean" from the body request.
My database is organized like that:
"cart": {
"itens": {
"0": {info here},
"1": {info here}
"2": {
"more info here",
"product": {
"avaliable": true"
"quantity": 231,
"ean": "0000001312"
}
continue listing until 47
But when I execute my cloud function:
exports.getItemByEan = functions.https.onRequest(async (request, response) => {
const db = admin.database();
const itens = db.ref();
const eanRef = itens.child('carrinho').child('itens');
const query = eanRef.orderByKey();
try {
const dataSnapshot = await eanRef.once('value');
response.send(dataSnapshot.val());
} catch (error) {
console.log(error)
}
})
});
But i need to get inside of an iten, and then inside "product" field and than get the "ean", but the result of this is like an Array insted of an object, and without the keys appearing:
[
{,
"product": {
"avaliable": true,
"quantity": 9183
"ean": "0000000000017",
},
{
"product": {
"avaliable": true,
"quantity": 131
"ean": "0000000044790",
},
},
.....continues
I want to things, understand why the result of the query is an Array and not an Object with the Keys before the itens like in the Firebase Database, and then how is the better way to find the specific product by Ean.
I can't even do like
const db = admin.database();
const itens = db.ref();
const eanRef = itens.child('cart').child('itens').child('product'); // This doesnt works, just returns nothing, why ?????
// Isn't "product" field inside the item ?
If your database keys are all numbers, then instead of an object, you will get an array with the same items, where the indexes of the array are the same as the keys of the nodes in the database. Your code needs to be prepared for this. So, if you want the client to receive an object instead of an array, you will have to convert it yourself.

Find nested object that contains a value

I have an object containing multiple other objects, inside these nested objects is an array containing multiple objects, each with a uid. I'm trying to loop over the objects and find the object that contains a particular uid.
My data looks like this
const data = {
"3c5671fde44f44f9ad59d59eb810d87e": {
"heading": "Heading 1",
"items": [
{
"content": {
"uid": "4fcd5f4af7a448d48463d4e0a11297d9"
}
},
{
"content": {
"uid": "31f975440a0a431592e127b2891cd142"
}
}
]
},
"ea80e8315b554c9bb40958a6cacf4b0c": {
"heading": "Heading 2",
"items": [
{
"content": {
"uid": "d6de8db4c2a74da6915a44d3964277d6"
}
}
]
}
}
The uid I want to search for is d6de8db4c2a74da6915a44d3964277d6 when found I want to return it's parent object so I can access the heading property.
Current code looks like this but it doesn't work, it's been a long day so I'm likely missing something really simple.
const currentUid = "d6de8db4c2a74da6915a44d3964277d6";
const currentHeading = Object.keys(data).forEach(section => {
return data[section].items.filter(item => {
return item.content.uid === currentUid;
});
});
When debugging it successfully evaluates to true when it finds the correct uid, it just doesn't return anything.
Any help welcome!
forEach is meant just for looping the array, use find to find the key of your object from Object.keys(data). And inside the callback use some instead of filter to check the existance. This solution will result in either the key of the object or null. To get the object, just check that a key is returned and then use that key to get the object:
const currentHeadingKey = Object.keys(data).find(section => {
return data[section].items.some(item => {
return item.content.uid === currentUid;
});
});
const currentHeading = currentHeadingKey != null ? data[currentHeadingKey] : null;
currentHeading is now either the whole object if found, null otherwise. You can access the heading property of that object.
Note: Since the callbacks of both find and some have only one statement in them, you can use the implicit return of arrow function to shorten the code:
const currentHeadingKey = Object.keys(data).find(section =>
data[section].items.some(item => item.content.uid === currentUid)
);
Consider using the Object.values() method instead, to extract the "parent heading" for the supplied uid.
Taking this approach, you can iterate the values of data, and filter those section values that contain items matching the uid. In the answer below, this is done via:
return items.some(item => item.content.uid === currentUid)
Finally, you can map() the filtered sections to acquire the corresponding heading(s) of section with matching uid items:
function findHeading(data, uid) {
return Object.values(data).filter(section => {
// Find any item with matching uid in this section, filter this section accordingly
return section.items.some(item => item.content.uid === currentUid)
})
.map(section => {
// Map heading from any sections matching item uid
return section.heading
});
}
const data = {
"3c5671fde44f44f9ad59d59eb810d87e": {"heading": "Heading 1","items": [{"content": {"uid": "4fcd5f4af7a448d48463d4e0a11297d9"}},{"content": {"uid": "31f975440a0a431592e127b2891cd142"}}]},"ea80e8315b554c9bb40958a6cacf4b0c": {"heading": "Heading 2","items": [{"content": {"uid": "d6de8db4c2a74da6915a44d3964277d6"}}]}
}
const currentUid = "d6de8db4c2a74da6915a44d3964277d6";
console.log(findHeading(data, currentUid))

React, Firebase: Access values of JSON and also get key value

I am beginner working with firebase, react. I am able to get the required data from firebase based on userEmail. But I am very confused in accessing the data.
firebase.database().ref('/users').orderByChild('email').equalTo(userEmail).on('value', data => {
console.log('data: ', data);
})
I get the following output:
data: Object {
"-Lhdfgkjd6fn3AA-": Object {
"email": "t5#gmail.com",
"favQuote": "this is it",
"firstName": "t5",
"lastName": "l5",
},
}
Please help me how to access all values ("-Lhdfgkjd6fn3AA-" , firstname, lastname, email and favQuote) into variables like: data.firstName, data.lastName, data.key, etc . Thank you.
let data = {
"-Lhdfgkjd6fn3AA-": {
"email": "t5#gmail.com",
"favQuote": "this is it",
"firstName": "t5",
"lastName": "l5",
},
};
console.log(Object.keys(data))//returning an array of keys, in this case ["-Lhdfgkjd6fn3AA-"]
console.log(Object.keys(data)[0])
console.log(Object.values(data))//returning an array of values of property
console.log(Object.values(data)[0].email)
Do need to be careful that the above code with the hardcoded "0" as index because it assumed that your data object has only one key. If you have more key, you can't simply replace index either because property of object has no predictable sequence
It's really a JavaScript question. I had to figure this out too. ...this works.
var p;
var thisLine;
p = docu.data();
for (var k in p) {
if (p.hasOwnProperty(k)) {
if (isObject(p[k])) {
thisLine = p[k];
Object.keys(thisLine).forEach(function (key, index) {
console.log(key, index);
});
}
}
}
function isObject(obj) {
return obj === Object(obj);
}
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.
So your first step is that you need to loop over the snapshot in your on() callback.
The second step is that you need to call Snapshot.val() to get the JSON data from the snapshot. From there you can get the individual properties.
firebase.database().ref('/users').orderByChild('email').equalTo(userEmail).on('value', snapshot => {
snapshot.forEach(userSnapshot => {
let data = userSnapshot.val();
console.log('data: ', data);
console.log(data.email, data.firstname);
});
})

Accessing Firebase data in a node with JS

So I have an object being returned from Firebase that looks like this:
{key: {name: "test", email: "test", id: "test"}}
How can I get the id out of this object?
If I do returnItem I get that object, so I tried to do returnItem[0] but it's not an array, and I've tried (Object.keys(tempSnap) but that just gives me the key not the object inside it.
This is my current code:
export function sendInvitation(email) {
firebaseRef.database().ref().child('users').orderByChild('email').equalTo(email).on("value", function(snapshot) {
let tempSnap = snapshot.val();
if(tempSnap != null) {
console.log(tempSnap);
}
});
return dispatch => firebaseRef.database().ref(`${userID}/invites`).push("This is a test Message!");
}
This is what it outputs:
Help would be awesome :D
If you already know id and it's a literal, then it's a matter of returnItem.id.
If you already know id and it's a variable, then it's returnItem[id].
If you don't know the keys and want to print all keys and their values, it's:
Object.keys(returnItem).forEach(function(key) {
console.log(key, returnItem[key]);
});
Update
Your new code shows the problem. 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 callback needs to handle the fact that it gets a list by looping over the results with snapshot.forEach():
firebaseRef.database().ref().child('users').orderByChild('email').equalTo(email).on("value", function(snapshot) {
snapshot.forEach(function(child) {
let tempSnap = child.val();
console.log(tempSnap);
});
});
Try this:
firebaseRef.database().ref().child('users').orderByChild('email').equalTo(email).on("value", function(snapshot) {
snapshot.forEach(function(child) {
let keys=child.key;
let ids=child.val().id;
)};
)};
you have:
users
keyid
email:email
name:yourname
id: test

Categories

Resources