How to get key of parent - javascript

I just want to get the stripe customer ID whenever a new payment method is added to my database.
I'm new to realtime databases and I just need some guidance.
var newPaymentMethodRef = functions.database.ref('/stripe_customers/{uid}/newPaymentMethod');
var stripe_customers = functions.database.ref('/stripe_customers/{uid}');
exports.newPaymentMethod = newPaymentMethodRef.onWrite(event => {
console.log("uid = ${uid}");
console.log("newPaymentMethod created");
});
I've tried
event.key
event.parent.key
event.ref("/stripe_customers/")
I'm obviously lost

If the Stripe customer ID is the value that is passed in the {uid} part if the call to the database, you can get it with:
exports.newPaymentMethod = newPaymentMethodRef.onWrite((change, context) => {
console.log(context.params.uid);
Also see the Firebase documentation on Realtime Database triggers.

Related

How to iterate a firebase database using javascript?

I need to iterate the users of my Firebase Database. I have a token for each user, and I want to send a notification to each user of the database.
My database looks like this:
console.log('Sending a notification to all users');
var ref = functions.database.ref('/users');
for (var token in ref){
console.log('Hello from: '+ ref.token);
}
Your ref is just a reference to a specific path in Firebase Realtime Database. You haven't queried it, so you don't have anything back yet. Try this:
console.log('Sending a notification to all users');
var ref = functions.database.ref('/users');
// Query the database
ref.once('value').then((usersSnapshot) => {
// Get back all the user records and iterate through them.
usersSnapshot.forEach((userRecordSnapshot) => {
// I'm guessing your record id is the token?
const token = userRecordSnapshot.key
// To get the other values, for example
const email = userRecordSnapshot.val().email
});
});```

Retrieving data on firebase having child key uid (javascript)

I am struggling how to retrieve data from firebase having a child key, such as uid.
here is the structure of my firebase.
Currently I am making an admin panel which can read the order placed by each user and render it through flatlist in react native, but it seems that I can't access their order because every time the user places an order it is stored on their unique User.id
I don't know how to make a reference to the User.id child like firebase.database().ref(orders/${AllUserId}/products)
You can use forEach loop to fetch ids and can get values as so
firebase.database().ref('order').on('value', (snapshot) => {
snapshot.forEach((child) => {
uid = child.key; // gives uid1
child.forEach((snap) =>{
var id = snap.key; // first iteration gives uid2
firebase.database().ref('order/'+uid+'/'+id).on('value', (snapchild) => {
snapchild.forEach((snapshotchild) =>{
console.log(snapshotchild.val());
});
});
});
});
});
This could be more insightful.

How to do CRUD operations in Firebase with CurrentUserId?

I'm creating a simple website and i'cant use firebase realtime databases crud operations with currentUserId.
My auth system working good; i can signIn/signUp/signOut on database. And i can write data to firebase with getting inputs from form.
//GETTING DATA WITH FORM
// Listen for form submit
document.getElementById('form').addEventListener('submit', submitForm);
// Submit form
function submitForm(e){
e.preventDefault();
// Get values
var name = getInputVal('name');
var sets = getInputVal('sets');
var reps = getInputVal('reps');
var weights = getInputVal('weights');
// Write data
writeData(name, sets, reps, weights);
// Clear form
document.getElementById('form').reset();
}
// Function to get form values
function getInputVal(id){
return document.getElementById(id).value;
}
//CRUD OPERATIONS
// Reference
var DataRef = firebase.database().ref('users/' + 'exercises/');
// Write data to database
function writeData(name, sets, reps, weights){
var newDataRef = DataRef.push();
newDataRef.set({
name: name,
sets: sets,
reps: reps,
weights: weights,
});
}
I didn't want to start reading, updating and deleting until I solved this id problem.
So how to do CRUD operations with each users with id? What can i do?
Are you asking how to write data in a location that is specific to the current user? If so:
var currentUser = firebase.auth().currentUser;
var DataRef = firebase.database().ref('users/' + currentUser.uid + '/exercises/');
Note that this only works if the current user is guaranteed to be already signed in. If you can't guarantee that, put the above code in an auth state listener.

Access Firebase database

I have a project with Firebase. I want to have access to the attribute "text" of my database with a cloud function as soon as there is a recent branch added to my database.
I am not get used to using their database.
My code in NodeJs is bellow :
exports.messageAnswer = functions.database.ref('/messages')
.onWrite(event => {
const snapshot = event.data;
const val = snapshot.val();
var textMsg = val.text;
var regex = "(bot)";
//var database = firebase.database();
if(!textMsg.match(regex) && textMsg.length > 0){
var id = new Date().getTime().toString();
var object = {
text : "I am the Cloud bot #" + id,
};
admin.database().ref('/messages').push(object);
}
return 0;
});
My problem is the fact that there is a "PUSH ID" : I don't know how to contourne this unique string to get the value of the attribute "text".
You can use wildcards to get the text attribute some something like this:
exports.messageAnswer = functions.database.ref('/messages/{pushid}')
.onWrite(event => {
for more info check this: https://firebase.google.com/docs/database/extend-with-functions
You can specify a path component as a wildcard by surrounding it with curly brackets; ref('foo/{bar}') matches any child of /foo. The values of these wildcard path components are available within the event.params object of your function. In this example, the value is available as event.params.bar
Your current code is being triggered whenever any data under /messages changes. From your description it seems you only want to be triggered when a new message is added. You do that by using onCreate instead of onWrite. In addition you'll want to listen for changes to a specific message, instead of to the entire /messages node:
exports.messageAnswer = functions.database.ref('/messages/{messageId}')
.onCreate(event => {
Also see Doug's blog post on these triggers: https://firebase.googleblog.com/2017/07/cloud-functions-realtime-database.html

Checking data in deep array with includes (Firebase retrieve data JS)

So I am new to the Firebase database and what I like about it is that I don't have to build a whole backend for just storing some simple data. What I am trying to do is pushing data to an array that I like to recieve from firebase. Then after that I would like to check if the email that was filled in, is included in the data from the firebase database. But because it's firebase and it has multiple arrays, objects etc I don't know how to check that. So the flow is: User fills in data, Applications makes a call to the firebase db and the Application is retrieving the current data from firebase. Then the Application will check if the data that is inputed is already there, and if so, will throw an alert that the data is already in the database. If not, the data will be submitted.
Also, I am wondering if this is the right way to retrieve data from the database:
Main.js
function writeUserData() {
var name = document.getElementById("name").value;
var email = document.getElementById("email").value;
firebase.database().ref('/aanmeldingen/').push({
username: name,
email: email,
});
var dbRef = firebase.database().ref().child('/aanmeldingen/');
dbRef.on('value', snapshot => {
const snap = snapshot.val();
const array = [];
array.push(snap);
console.log(array);
const res = array.includes(email);
console.log(res);
console.log(email);
});
}
Output in console
As you can see this returns multiple data. The include function will check on the submitted emailadress. This returns false even I had inputted "info#webpack.com". How can I check the right data object? It has to check all objects under "0" and return in the console if the submitted emailadress is already there.
I haven't tested it yet but i hope you get the idea. Also this is not the most efficient way to do this.
function ifEmailExist(arr,email){
var _t = 0;
for(var x in arr){
for(var y in arr[x]){
if(arr[x][y].email){
if(arr[x][y] === email){
_t++;
}
}
}
}
return _t;
}
Usage:
if(ifEmailExist(arr,"info#webpack.com") > 0){
//do stuff
}
You should use child_added instead of value. Whenever a new node is added in database, child_added will trigger and then you can take action on the data.
var dbRef = firebase.database().ref().child('aanmeldingen');
dbRef.on('child_added', snapshot => {
var username = snapshot.val().username;
var email = snapshot.val().email;
console.log(username);
console.log(email);
});

Categories