Firebase - Set Firebase references dynamically based on user input - javascript

I'm trying to set firebase references dynamically. What I know from the doc is firebase set references at the initial state. As long as I try to make it dinamic it give me permission error.
For example I want to get fruit name from the input, so the code:
$('.fruit').click(function(){
var name = $(this).text();
getFuitName(name);
});
function getFruitName(name){
var fruit = firebase.database().ref('fruit/' + name );
fruit.once('value', function(snapshot) {
console.log(snapshot.val().name);
});
}
What should I do? Any special approach to do this?

I found the solution. I've to separated the database references like this:
var database = firebase.database(); // I add this line
$('.fruit').click(function(){
var name = $(this).text();
getFuitName(name);
});
function getFruitName(name){
var fruit = database.ref('fruit/' + name ); //and then modified this line
fruit.once('value', function(snapshot) {
console.log(snapshot.val().name);
});
}

Related

Firebase how to find child knowing its id but not its parent's id (js)

I have a firebase realtime database (not cloud) structure like:
users
kasdf872ajsda //user id
auiiq6d182g1 //list id
c: <mycontent> //list content
i know the list id (in this case auiiq6d182g1) and i want to retrieve <mycontent>, but i don't know the user id kasdf872ajsda , because what i'm going to retrieve is probably not from the user currently using the website (and i'm not setting any database rules for "read" in fact, only for "write" is that correct?).
What i'm doing right now is this (not working):
var ref = firebase.database().ref().child('users');
ref.child(listID).once("value", function(snapshot) {
var snap = snapshot.val();
myContent = snap.c;
});
You could put your reference to users first: var ref = firebase.database().ref('users');
Then loop through:
ref.once('value').then((snapshot)=>{
snapshot.forEach(function(data) {
if (data.key == <YOUR_LIST_ID>) {
//you can access data.c here...
}
});
});
Found the solution, if someone should encounter the same issue:
ref.once("value", function(snapshot) {
snapshot.forEach(function(data) {
snap = data.child(<YOUR_LIST_ID>).child('c').val();
if (snap != null){
myContent = snap;
}
});
});
also ref contrary to what everyone says has to be:
var ref = firebase.database().ref().child('users');
this doesn't work:
var ref = firebase.database().ref('users');

Manage Filter ID Gmail

I am trying to create a filter for every people's email in a group. However, sometimes the a person's email can changes like adding new email or change to another mail email. That means I have to update the filter accordingly. I tried to create filter with ID that with the person's name. So I can retrieve that filter to modify it. However, it seems that the Gmail filter's ID are created automatically.
var filter = Gmail.newFilter()
var email = 'something#some.com'
filter.id = 'person'
filter.criteria = Gmail.newFilterCriteria()
filter.criteria.query = email
filter.action = Gmail.newFilterAction()
filter.action.addLabelIds = ['Label_1']
Gmail.Users.Settings.Filters.create(filter, 'me')
When I get back the filter, it will say that it cannot be found
var filter2 = Gmail.Users.Settings.Filters.get('me', 'person')
This will return Not Found error even I can see the filter in setting in my Gmail. The actually ID for the filter I created above is ANe1Bmgel8OKlEXD-uArX77ISk35Lph1MbWWjA.
My question is what's the good way to manager filters through changes, keep them updated?
Instead of:
Gmail.Users.Settings.Filters.create(filter, 'me');
Try:
var filterProps = Gmail.Users.Settings.Filters.create(filter, 'me');
var filterId = filterProps.id;
Per the API documentation for creating a filter,
If successful, this method returns a Users.settings.filters resource in the response body.
The code above worked for me in a similar situation. To keep track of the filterId outside of Gmail, you could then tie the person's name to the id via the property service:
PropertiesService.getScriptProperties().setProperty(nameVar, filterId);
and then retrieve it like so:
PropertiesService.getScriptProperties().getProperty(nameVar);
Per the API documentation for a Filter resource:
id: string The server assigned ID of the filter.
Thus, you cannot assign the ID, and any value you set for it in the call to .create is ignored.
You can still programmatically retrieve this filter, using .list and Array#filter, e.g.
function getAllFilters_(userId) {
const options = {};
const filters = [];
do {
var search = Gmail.Users.Settings.Filters.list(userId, options);
if (search.filter && search.filter.length) {
Array.prototype.push.apply(filters, search.filter);
options.pageToken = search.nextPageToken;
} while (options.pageToken);
return filters;
}
function getFiltersWithCriteria_(filterList, criteria) {
// `criteria` is an object of parameters that must be exactly matched in the filters' criteria property
const props = Object.keys(criteria);
const matches = filterList.filter(function (gFilter) {
// gFilter is a https://developers.google.com/gmail/api/v1/reference/users/settings/filters#resource
var fCriteria = gFilter.criteria;
return props.every(function (prop) {
return criteria[prop] === fCriteria[prop];
});
});
return matches;
}
function foo() {
const filters = getAllFilters_("me");
const matched = getFiltersWithCriteria_(filters, {
from: "george#example.com",
hasAttachment: true
});
console.log({message: "Matching filters", matches: matched});
}

Trying to delete a multi-path firestore field document with the batch method

I'm trying to delete a field document with multi-path location with the
firestore batch method. I used to do it with the update method on Real Time Database. Now I don't really know how to do it on Firestore.
deleteVenueFromEvent(event)
{
var eventkey = event.$key;
var venuekey = event.venue.venuekey;
var batch = this.afs.firestore.batch();
var eventRef = this.eventCollection.doc(eventkey).ref;
batch.update(eventRef, { venue: null });
var deleteVenueRef = this.venueCollection.doc(venuekey).collection('events').doc(eventkey).ref;
batch.delete(deleteVenueRef);
batch.commit().then(function() {console.log('Batch Delete')});
}
I find the way to do it with the following code :
var deleteVenueRef = this.venueCollection.doc(venuekey).ref;
batch.update(deleteVenueRef, {['events.' + eventkey] :firebase.firestore.FieldValue.delete()});

Remove item from firebase array with value using jquery

I want to remove a value from firebase database with value using jquery.
I want to delete 235 value from the firebase.
I tried..
var dbRef = new Firebase("https://afgani-cinemas.firebaseio.com/");
var showId = getUrlParameter('showId');
var bookings = dbRef.child('bookings/'+showId);
function removeFromFB(seatId){
dbRef.orderByValue().equalTo().on('child_added', function(snapshot){
snapshot.dbRef().remove();
});
}
removeFromFB(235);
Any suggestions in my code. Its not working!!!
getting warning like this
firebase.js:40 FIREBASE WARNING: Using an unspecified index. Consider adding ".indexOn": ".value" at / to your security rules for better performance
Try using this code snippet
var bookings = firebase.child('root/321');
function removeFromFB(valu){
bookings.on('child_added', function(data) {
if(data.val()==valu){
bookings.child(data.key()).remove();
}
});
}
removeFromFB(deleteValue);
in your case "deleteValue" will be 235

Firebase Web retrieve data

I have the following db structure in firebase
I'm trying to grab data that belongs to a specific user id (uid). The documentation has the following example:
firebase.database().ref('/users/' + userId).once('value').then(function(snapshot) {
var username = snapshot.val().username;
// ...
});
But how can I retrieve data from my example without knowing the unique key for each object?
Update:
I tried a new approach by adding the user id as the main key and each child object has it's own unique id.
Now the challenge is how to get the value of "title".
firebase.database().ref('/tasks/').orderByChild('uid').equalTo(userUID)
Well that is pretty straightforward. Then you can use it like this:
return firebase.database().ref('/tasks/').orderByChild('uid').equalTo(userUID).once('value').then(function(snapshot) {
var username = snapshot.val().username;
// ...
});
Of course you need to set userUID.
It is query with some filtering. More on Retrieve Data - Firebase doc
Edit: Solution for new challenge is:
var ref = firebase.database().ref('/tasks/' + userUID);
//I am doing a child based listener, but you can use .once('value')...
ref.on('child_added', function(data) {
//data.key will be like -KPmraap79lz41FpWqLI
addNewTaskView(data.key, data.val().title);
});
ref.on('child_changed', function(data) {
updateTaskView(data.key, data.val().title);
});
ref.on('child_removed', function(data) {
removeTaskView(data.key, data.val().title);
});
Note that this is just an example.

Categories

Resources