how can I toggle a boolean parameter in javascript? - javascript

I want to toggle a value called 'session' and then, update this value.
i've tried to do session=!session, but that didn't work.
session is a parameter inside a object, this object are displayed on my nosql database, i'm using the realtime database from firebase.
however session:true and session:false works
obs: English isn't my first lenguage, so sorry if I used wrong words.

Since you want to write a value to a path based on its existing value, you'll want to use a transaction.
Something like:
const userRef = ref(db, `/usuários/${fistKey}/session`);
runTransaction(userRef, (session) => {
if (session) {
return !session
}
return true; // 👈 default value
});

Related

Pass a variable into a query (Firebase)

this is really frustrating me I hope you kind people can assist me.
I have a firebase firestore db that stores info about properties and cities. All properties contain a key:value pair called location_city. It is a string that stores the City that the property resides in.
I have made a dropdown box on a webpage with a list of available cities. The idea is to dynamically display properties from the selected city, by means of the .where() method. The third parameter accepted by the method is the string you want to query against.
I want to pass the text value of the dropdown list into the query.
Here's my code:
let selectedCityViewHomes;
function getDropdownSelection(sel) {
selectedCityViewHomes = sel.options[sel.selectedIndex].text;
selectedCityViewHomes.toString();
}
db.collection('Homes')
.where('location_city', '==', selectedCityViewHomes)
.get()
.then(snapshot => {
snapshot.docs.forEach(doc => {
renderHome(doc);
});
});
The query method only seems to work if you manually enter a string into the parameter and does not seem to allow you to pass a variable (which is a string) into the method.
I have tried concatenating "'" either side to mimic 'Manchester', for example and this did not work either.
TIA
Charlie
EDIT: I found where i had gone wrong, it was an issue of scope i think. I fixed it by creating a function which wrapped the db.collection code and passed in the variable as an argument.
const updateHomesViewHomes = (input) => {
db.collection('Homes').where('location_city', '==', input).get().then((snapshot) => {
homesViewHomes.innerHTML = "";
snapshot.docs.forEach(doc => {
renderHome(doc);
});
});
};
Thanks for the replies, hope this helps someone.

Firebase cloud functions: How to get the reference to the document with wildcard notation?

Here are what I am trying to do with Firebase cloud functions:
Listen to change in one of the documents under 'public_posts' collection.
Tell if the change is in the 'public' field from true to false
If true, delete the document that triggered the function
For steps 1&2, the code is straightforward, but I don't know the syntax for step 3. What would be the way to get the reference of the document that triggered the function? That is, I'd like to know what would be the code in question for the empty line below:
exports.checkPrivate = functions.firestore
.document('public_posts/{postid}').onUpdate((change,context)=>{
const data=change.after.data();
if (data.public===false){
//get the reference of the trigger document and delete it
}
else {
return null;
}
});
Any advice? Thanks!
As explained in the doc:
For onWrite and onUpdate events, the change parameter has before and
after fields. Each of these is a DataSnapshot.
So, you can do as follows:
exports.checkPrivate = functions.firestore
.document('public_posts/{postid}').onUpdate((change, context)=>{
const data=change.after.data();
if (!data.public) { //Note the additional change here
const docRef = change.after.ref;
return docRef.delete();
}
else {
return null;
}
});
Update following Karolina Hagegård comment below:
If you want to get the value of the postid wildcard, you need to use the context object like: context.params.postid.
Strictly speaking you get the document id, not its DocumentReference. Of course, based on this value, you can rebuild the DocumentReference with admin.firestore().doc(`public_posts/${postid}`); which will give the same object than change.after.ref.
The onUpdate listener returns a Change object (https://firebase.google.com/docs/reference/functions/cloud_functions_.change)
To get the updated document you would do:
change.after.val()
To remove the document you would do:
change.after.ref.remove()

Firebase orderByKey().startAt() not working as expected. What's wrong?

I'm trying to get firebase data from a node which uid must start with a passed string.
I tried a code but I always get the same data. The database data is as following:
And I'm using the following code:
var ref = firebase.database().ref("restaurantes/history");
ref.orderByKey().startAt(userUID).once("child_added", function(snapshot) {
snapshot.forEach(child => {
if(child.key == "orders")
{
console.log(child.val());
_.each(child.val(), (value, key) => {
arrtmp.push(value)
})
}
})
If user is "FKQLlqa" I should get the history data shown in the picture. If I user is "abc" I shouldn't get any data. But I always get the data shown in the picture. Should I use another way of querying? Or I should use a key field inside orders and payments data?
Regards!
Try the following:
var ref = firebase.database().ref("restaurantes/history");
ref.child(userUID).once("value", function(snapshot) {
if (snapshot.exists()) {
console.log(snapshot.val());
}
else {
console.log("different user");
});
This will check if the snapshot that contains the userId (added as a parameter in the child() method), already exists in the database then you will be able to retrieve the data under the userId.
For reference:
https://firebase.google.com/docs/reference/js/firebase.database.DataSnapshot#exists
Peter's answer is the correct solution. I'm merely adding this for completeness.
When you call orderBy... on a Firebase reference, the database orders all child nodes on the key/value/child that you specify.
If you then subsequently call startAt(...) on the query, it finds the (first) node that starts with that value and starts returning all results from there. So if you start at FKQLlqa, it will start returning keys at FKQLlqa and then return all keys after it.
If you want to return the child node(s) with a specific key/value/child, you'd use equalTo(...). So:
ref.orderByKey().equalTo(userUID).once("child_added", function(snapshot) {
...
But as Peter said already, this is just a more expensive way to look up a child with a known key. I highly recommend using his better approach: ref.child(userUID).once("value".

Match value of array from database object in Firebase Cloud Functions

This is my first app project using Google Cloud Functions & Firebase. I'm trying to find away to get a single value of the array that I'm returning and compare it to a set variable and if it matches, update another child's value in that same account.
My App users can add records to the database under their login/user_id that is stored in the database. I'm trying to get a list of the "RecordName" that is a child under that login/user_id that every user has stored in their account.
So basically every "RecordName" in the entire database. When I want to run specials for those records, I need to match the name of that record to the name of the record I have on special and if there is a match, update another child value under that user's account ("special" = true.). This way, when they load their app next time, I have it highlighting that record so they know it's on special.
When I use..
const ref = admin.database().ref(`/store`);
...with the following code...
ref.on('value', function(snapshot) {
// puts ALL items of the object into array using function ..
console.log(snapshotToArray(snapshot));
});
... and the function...
function snapshotToArray(snapshot) {
var returnArr = [];
snapshot.forEach(function(childSnapshot) {
var item = childSnapshot.val();
item.key = childSnapshot.key;
returnArr.push(item);
});
return returnArr;
};
... I get the entire array just as it is in the database:
-store
-{ones_users_id}
-recordname: value1
-special: false
-{anothers_users_id}
-recordname: value2
-special: false
ect. ect.
If my record on special is called, "Newbie Record", what would be the best way to take out every individual value for the key: "recordname" from the array, compare each one to var = "Newbie Record" and if they match, update the value of the key: "special" to be true?
I'm new to JSON and NodeJS, I've been searching on here for answers and can't find exactly what I'm looking for. Your feedback would be very helpful.
It sounds like you're looking to query your database for nodes that have "recordname": "Newbie Record" and update them.
An easy way to do this:
const ref = admin.database().ref(`/store`);
const query = ref.orderByChild("recordname").equalTo("Newbie Record");
query.once('value', function(snapshot) {
snapshot.forEach(function(child) {
child.ref.update({ special: true })
});
});
Main differences with your code:
We now use a query to read just the nodes that we want to modify.
We now use once() to read the data only once.
We loop over the children of the snapshot, since a query may result in multiple nodes.
We use the reference of each child and then update its special property.
I recommend reading a bit more about Firebase queries in the documentation.

firebase - filter on not equal to

I have a firebase database from which I would like to retrieve all items except the items having a specific value. A function like notEqualTo(), so to say.
firebase.database()
.ref().child('/snippets/')
.orderByChild('description')
.notEqualTo('dontDisplay')
.on('value',function(snap) {
// Working with the right snapshot
}
This obviously does not work since notEqualTo is not a function. I also tried passing a function to equalTo but this doesn't work either:
firebase.database()
.ref().child('/snippets/')
.orderByChild('description')
.equalTo(function (descr) { descr !== 'dontDisplay'; })
.on('value',function(snap) {
// Working with the right snapshot
}
What's the right way to filter on items not having the description 'dontDisplay'?

Categories