I am using firebase and I want to only retrieve childs with a specific value (activiteId) for a given key ("associationId")
What I tried:
firebase.database().ref().child("collectivites").child(collectiviteId).child("evenements").orderByChild("associationId").equalTo(activiteId).once("value", function (snapshotAssociationEvenements) {
const data = snapshotAssociationEvenements.val();
if (data){
console.log(data);
}
});
The problem :
The child is displayed in the console but if I do console.log(snapshotAssociationEvenements.val().associationId); the console returns undefined
What have I done wrong ?
My db
Thank you !
Try the following:
firebase.database().ref().child("collectivites").child(collectiviteId).child("evenements").orderByChild("associationId").equalTo(activiteId).once("value", function (snapshotAssociationEvenements) {
snapshotAssociationEvenements.forEach(function(childSnapshot) {
var associateId=childSnapshot.val().associationId;
});
Your snapshot is at the child evenements, then you loop inside the random id using the forEach and you will be able to access the children under that id.
Related
I am deleting a FRTDB node, I want to access deleted data from that node. the functions looks as follow:
exports.events = functions.database.ref('/events/{eventId}').onWrite(async (change, context) => {
const eventId = context.params.eventId
if (!change.after.exists() && change.before.exists()) {
//data removed
return Promise.all([admin.database().ref(`/events/${eventId}/dayofweek`).once('value')]).then(n => {
const pms = []
const days = n[0]
days.forEach(x => {
pms.push(admin.database().ref(`${change.before.val().active ? 'active' : 'inactive'}/${x.key}/${eventId}`).set(null))
})
return Promise.all(pms)
});
else {
return null;
}
})
The probem I am having is that
admin.database().ref(`/events/${eventId}/dayofweek
do not loop the data because it seems data is no longer there so the forEach is not working. How can I get access to this data and get to loop the deleted data?
Of course you won't be able to read data that was just deleted. The function runs after the delete is complete. If you want to get the data that was just deleted, you're supposed to use change.before as described in the documentation:
The Change object has a before property that lets you inspect what was
saved to Realtime Database before the event. The before property
returns a DataSnapshot where all methods (for example, val() and
exists()) refer to the previous value. You can read the new value
again by either using the original DataSnapshot or reading the after
property. This property on any Change is another DataSnapshot
representing the state of the data after the event happened.
The data that was deleted from the database is actually included in the call to your Cloud Function. You can get if from change.before.
exports.events = functions.database.ref('/events/{eventId}').onWrite(async (change, context) => {
const eventId = context.params.eventId
if (!change.after.exists() && change.before.exists()) {
//data removed
days = change.before.val().dayofweek;
...
})
I am trying fetch records from mongoDB through mongoose
router.route('/testaa')
.get(function(req,res){
fisSite.find(function(err, retVal) {
var x = [];
for(var i =0;i<retVal.length;i++){
x.push(retVal[i].site);
}
res.json(x)
});
})
The above code is giving undefined values.
undefined
undefined
undefined
.....
Please help to run the for loop inside node.js so that i can use extract data from array.
Currently what you are doing is you are getting all the document fields and then using only one from it. You can optimize the query using select method which will only retrieve particular field only rather than all fields :
[Note : id field is added by default, hence to remove it in select we specifically mention it using -_id. You can remove -_id if you want to maintain ID inside the response document.]
fisSite.find({}).select('site -_id').exec(function(err, docs)){
if(err){
return res.json({ status : false, message : 'Error Occured.'} );
}
else if(!docs){
return res.json({ status : false, message : 'No documents found.'} );
}
else{
return res.json({ status : success, message : 'Documents found.', data : docs} );
}
}
Imagine you have 10 fields in each document and find results 100 documents, you only need site field from those 100 documents,however unnecessarily you are calling remaining 900 fields.
I have used Lean.exec within Mongoose.
router.route('/site')
.get(function(req,res){
fisSite.find().lean().exec(function(err, retVal) {
var x = [];
for(var i =0;i<retVal.length;i++){
x.push(retVal[i].site);
}
res.json(x)
})
});
Try to add an empty search query to select all documents
Try to change
From this:
fisSite.find(function(err, retVal)
To this:
fisSite.find({}, function(err, retVal)
Also try to do a console.log(retVal) to check if your find actually returns any values.
I have the following database setup in Firebase:
I am trying to write a script that searches within media (in all users) and returns a match if any particular media url matches the url argument I pass through. And if a match is returned I would like to remove this media key/node. However, my script is just returning null. Any ideas?
const ref = firebase.database().ref('/users/');
const url = 'https://XXXXXX.s3.amazonaws.com/profiles/william/1478471907-me.jpg';
return ref.child('media').orderByChild('url').equalTo(url).once("value").then(function(snapshot) {
console.log(JSON.stringify(snapshot.val()));
});
Ok thanks to Imjared's feedback I've found a solution - including a way to remove the node:
// reference the media, B4K... could be an variable to target the correct key
const ref = firebase.database().ref('/users/B4KWeemv78R2GP7Jqul2f70kVM73/media');
return ref.orderByChild('url').equalTo(url).once("value").then(function(snapshot) {
// get the key of the respective image
const key = Object.keys(snapshot.val())[0];
// delete image node from firebase
ref.child(key).remove();
return {
success: 1,
message: 'Image deleted.'
};
}
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.
I am working on an app to store data offline. My problem is when I try to retrieve the data from local storage for update/edit, it keeps calling only the id of the first item, and not calling the id of the data in view.
Please what am I doing wrong?
Here is my code for loading employees:
// load cases from localStorage
var employees;
if (localStorage.getItem('employees')) {
employees = JSON.parse(localStorage.getItem('employees'));
} else {
// If no cases, create and save them
employees = [];
// offling storing of our cases
localStorage.setItem('employees', JSON.stringify(employees));
}
// show case listing in list view page
var showEmployees = function () {
//erase existing content
$('#employee_list').html('');
//insert each employee
for (var i = 0; i<employees.length; i++) {
addEmployees(employees[i]);
}
};
Here is my code to add an employee to list view:
//add an eliment to list view
var addEmployees = function (empData) {
//HTML content of one list element
var listElementHTML = '<li><a class="employee_list" ui-btn ui-btn-e ui-btn-icon-right ui-icon-carat-r" data-transition="fade" data-split-icon="delete" href="#item'+empData.id+'">' + empData.employeename + '<br> ' + empData.dateofbirth + '</br></a></li>';
//appending the HTML code to list view
$('#employee_list').append(listElementHTML);
};
Here is my code for Edit function:
//User input to edit form
$('#edit_employee_page').on('click' , function () {
var editEmployee = JSON.stringify({
id: employees.length+1,
employeeno: $('#employeeno').val(),
employeename:$('#employeename').val(),
stateoforigine:$('#stateoforigine').val(),
employeephone: $('#employeephone').val(),
dateofbirth:$('#dateofbirth').val()
});
//Alter the slected data
localStorage.setItem("employees", JSON.stringify(employees));
return true;
});
for (var i in employees) {
var id = JSON.parse(localStorage.getItem(employees[i]));
}
Here is my code for the Edit button:
//register Edit button
$('.edit_button').live('click', function (e) {
alert('I was Cliked!');
e.stopPropagation();
$.each(employees, function(a, b) {
//if(b.id == employees[i]){
$('#id').val(b.id);
$('#employeeno').val(b.employeeno);
$('#employeename').val(b.employeename);
$("#stateoforigine").val(i.stateoforigine);
$('#employeephone').val(b.employeephone);
$('#dateofbirth').val(b.dateofbirth);
$("#id").attr("readonly","readonly");
$('#employeeno').focus();
$.mobile.changePage('#edit_employee_page');
return false;
//}
});
});
Here is my local Storage:
[
{"id":1,
"employeeno":"DEF/234/20014",
"employeename":"Bill Gates",
"stateoforigine":"Osun",
"employeephone":"080765432",
"dateofbirth":"12/11/1965"},
{"id":2,
"employeeno":"DEF/234/20014",
"employeename":"Bill Gates",
"stateoforigine":"Osun",
"employeephone":"080765432",
"dateofbirth":"12/11/1966"},
{"id":3,
"employeeno":"DEF/234/20014",
"employeename":"Bill Gates",
"stateoforigine":"Osun",
"employeephone":"080765432",
"dateofbirth":"12/11/1966"},
{"id":4,
"employeeno":"DAST/003/2003",
"employeename":"Gold Base",
"stateoforigine":"",
"employeephone":"",
"dateofbirth":"12/03/1986"}
]
Thanks for helping me out
The way you are storing your employees into localStorage is correct, but the way you are getting them out is incorrect. You stored your employees by stating:
localStorage.setItem("employees", JSON.stringify(employees));
So, in order to retrieve them, you must use:
var employees = JSON.parse(localStorage.getItem("employees"));
You see, you stored the data as a string with a key of "employees"; therefore, you can only retrieve it by that key. Since all data stored in localStorage is saved as a string, you must use JSON.parse() to convert the data back into an object - an array in this case. Then you can iterate over your employees.
Update:
You should be running this code as soon as the page is rendered (see below). I'm not sure how you're doing that - if you're using an IIFE or jQuery's document.ready() function. I don't think it's necessary to store an empty array into localStorage if none were loaded initially, so, I took your else clause out.
var employees = [];
if (localStorage.getItem('employees') !== null) {
employees = JSON.parse(localStorage.getItem('employees'));
}
Debug this line-by-line when it runs and make positive your employees variable contains data. If it doesn't contain data, well then, there's nothing to edit.
If, however, there is data, then execute your showEmployees() function. Oddly, I'm not seeing in your code where you actually call this. Is it bound to a button or action in your UI? Also, what is that for loop doing after your $('#edit_employee_page') click event function? It's trying to read data from localStorage improperly and it does nothing.
I think if you simply stepped through your code one line at a time using breakpoints and desk-checking your inputs/outputs you'd find out where you're going wrong.
It also appears that there's a disconnect in your code. May be you left out some lines; you define a string editEmployee but out of the blues you store JSON.stringify(employees) whereas employees is not defined in your code:
$('#edit_employee_page').on('click' , function(){
var editEmployee = JSON.stringify({
id: employees.length+1,
//........
});
//Alter the slected data
localStorage.setItem("employees", JSON.stringify(employees));
return true;
});
I had a similar task to do . I did it this way.
I passed the dynamic Id to be passed as an id attribute
id="'+empData.id+'"
and then inside the
$('.edit_button').live('click', function (e) {
alert('I was Cliked!');
var empId=$(this).attr('id');
rest of the code is same.