Pass a variable into a query (Firebase) - javascript

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.

Related

how can I toggle a boolean parameter in 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
});

Could Not find Variable FieldValue, React Native/Firebase

Trying to remove an item from the firebase array using arrayRemove but I'm getting the following error:
ReferenceError: Can't find variable: FieldValue
const removeItemHandler = () => {
//this logs the array item like is should, dont think this value is the issue
console.log(props.item)
console.log(props.currentNote)
//removes note from the notes array
db.collection('users').doc(userEmail)
.collection('books').doc(props.currentBook)
.collection('specific').doc(props.currentNote).update({
notes: FieldValue.arrayRemove(props.item)
})
showRemoveButton(false)
}
I was following the example linked below, really not sure why my, very similar situation is giving me this error. Thank you!
https://firebase.googleblog.com/2018/08/better-arrays-in-cloud-firestore.html
also, keep in mind that props.item is referencing the array items name, I checked the type and the value with the console.log's and it is correct. Confident that is not part of the issue.
You are accessing FieldValue which is undefined. You cannot access it directly.
You can access it via firebase.firestore.FieldValue or if you imported firestore directly then firestore.FieldValue. So change your code like this :
const removeItemHandler = () => {
//this logs the array item like is should, dont think this value is the issue
console.log(props.item)
console.log(props.currentNote)
//removes note from the notes array
db.collection('users').doc(userEmail)
.collection('books').doc(props.currentBook)
.collection('specific').doc(props.currentNote).update({
notes: firebase.firestore.FieldValue.arrayRemove(props.item)
notes: firestore.FieldValue.arrayRemove(props.item) // or if you are imported firestore
})
showRemoveButton(false)
}

How to update a field inside a list in firebase?

I have this collection in Firebase
I have tried to modify the value within the map notes of a specific subject, I could not do it and I have tried in several ways without success
I would really appreciate a little help.
I get the data in that way, but I can not update that data.
this.firestore.collection('school').doc('254')
.get().toPromise().then(doc => {
if (doc.exists) {
const student = doc.data().class.find(value => {
return value.name === 'john';
});
console.log('student', student);
/*
Here edit student.notes.math = newValue
*/
}
});
PD: I'm currently work with Angular 7.
I don't see that your code attempts to update the document that you found. Changing the data in memory doesn't change the contents of the document. You will have to write additional code to update the document with your changes to the class field.
See:
Firestore: How to update specific field of document?
The documentation
this.firestore
.collection('school')
.doc('254')
.update("class", NEW_FIELD_CONTENTS)
You will need to provide the entire contents of the updated class field. Firestore doesn't have any operations that let you update an array item at a specific index.

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".

Stripped Attributes with toJSON/toObject

I have something like the following code:
User.findOne(id)
.exec((err, user) => {
Pets.find(_.pluck(user.pets, 'id'))
.populate("toys")
.exec((err, petsWithToys) => {
user.pets = petsWithToys;
return res.ok({ user: user });
});
});
When I look at the response in the client I don't see the toys array inside the pet.
I thought maybe this was due to overriding the toJSON function in my User model but even when removing it I get the same behavior.
Also, I've found out that if I assign the values to a new property that is not defined in the model, I do see the values at the client. I.e. if I do
user.petsNew = petsWithToys;
I will see the fully populated property.
I've seen the documentation of toObject where is says it removes instance methods (here) but I am not sure why the collection is considered a method and don't understand how after changing the value it is still removed.
Any comments/explanations/workarounds?
P.S. Tried to step through the code but can't step into toObject...
Add user = user.toJSON(); before user.pets = petsWithToys;
Check https://stackoverflow.com/a/43500017/1435132

Categories