I'm trying to use the sys.data.createQuery() method that is described in the docs. I have an entity called 'companies' and I'm trying to retrieve all of the companies like this:
var companies = sys.data.createQuery('companies');
But this isn't working, is there another way of getting all of the records of an entity?
You need to execute the query and the iterate over the results like this:
var query = sys.data.createQuery('companies');
// add filters to the query as you want here
var records = sys.data.find(query);
while (records.hasNext()) {
var record = records.next();
sys.logs.info(record.label());
}
Related
firebase snippit
Hello all. I am creating a web app that pulls from a firebase realtime database I have created. Using javascript I would like to pull the data from a specific node (i.e. "8").
I will then use the keys and values from the node in the web app.
What js/firebase code do I need to pull data from any specific node?
Below is the code we have tried. Long term goal is to pull data from a random node, but right now I just to find out how to pull from a specific node. Since the nodes are always going to be a number from 0-49, I don't need to use "length of array" functions when randomizing. I will use "Math.floor(Math.random() * 49" to give me a random number which I can pass into the index value for the node when I figure out how to access one specifically.
ref = firebase.database().ref('articles/');
function setupObservers() {
ref.on('value',function(snapshot){
console.log(snapshot.val())
let articleArray = []
for(key in snapshot.val()) {
let articleKeys = snapshot.val()[key]
articleArray.push(articleKeys)
}
randomArticle(articleArray)
})
}
function randomArticle(articleArray) {
let random = articleArray[Math.floor(Math.random() * articleArray.length)]
console.log(random)
}
setupObservers()
Thanks in advance!!
To read the value from a specific child node of which you know the key, you simply do:
ref = firebase.database().ref('articles');
ref.child("8").on('value',function(snapshot){
console.log(snapshot.val())
});
This question has been asked before, but none of the solutions provided seem to help my problem:
I have an array of data on Firebase, that I loop through to generate content in my app, using a "for" loop and therefore an index value. This works fine with the predetermined sets of data, as the IDs are simple array numerics but when a user adds some new data, which is added to the array with push(), firebase creates a unique node key (such as -KyWRU7RRCE_V1w_OiZx) for the new set of data which for some reason prevents my loop from working (no errors shown in console).
If I go to firebase and manually ensure that the new set of data has a numeric value, loop starts working again. How do I make it so that when the user pushes new data to the array, the key being generated is numeric? I tried this:
// Push new routine to Firebase.
var firebaseRef = firebase.database().ref();
var createdExercise = JSON.parse(localStorage.newRoutine);
$("#save").click(function()
{
firebaseRef.child("workouts").key(some_indexed_value).push(createdExercise);
});
but the console returns the following error: Uncaught TypeError: firebaseRef.child(...).key is not a function.
In case it is useful, here is the loop I am using:
// Initialize Firebase.
firebase.initializeApp(config);
// Reference data.
var dbRef = firebase.database().ref().child("workouts");
// Sync with Firebase in real time.
dbRef.on("value", snap =>
{
var workouts = snap.val();
for (var i = 0; i < workouts.length; i++)
{
var routine = workouts[i].title;
var time = 3;
var exercises = workouts[i].exercises;
var icons;
$("#cardList").append(createCards(routine));
}
});
And a pic of my JSON data on Firebase:
Answer to your question is using .set() instead of .push() like this
firebaseRef.child("workouts").child(some_indexed_value).set(createdExercise);
this will create a node under workouts with your custom key.
but it is recommended to use push keys and use forEach() method to get the result than using for loop
I am trying to write a Firebase Cloud Function that takes all the users from my database and edits values within them. However, in order to do that I need a quick way for the code in my Cloud function to receive all of the user-ids from the database. For now, I have the function print the data it gets from the database so I know what I am working with.
The result is this:
{"WNGOuQqZhZSo5UFovgmgEAVX3Gz1":{"displayName":"jack","email":"test2#gmail.com"},"aRaZVJorkYNwCSzAbMkNJiGwzJm2":{"displayName":"testing","email":"testing#gmail.com"}}
I just need the two userIds instead.
This is the part of database I am working with:
This is the code:
If anyone knows what I need to change I would really appreciate it! Thanks!
I think you need to have a for - in loop over value. Below is the pseudocode -
var value = snapShot.val();
let namesArray = [];
for (var key in value) {
if (value.hasOwnProperty(key)) {
namesArray.push(key);
}
}
As with what jaibatrik said, you need to iterate over your objects.
You can't get the key without fetching the whole object.
In addition to running a for loop you can run a forEach over the snapshot.
const uids = [];
snapShot.forEach(single => {
uids.push(single.key);
});
The other option is to get all the keys from the snapShot.val() object.
const value = snapShot.val();
const uids = Object.keys(value);
Both ways are effectivly the same thing, just a preference on which way you prefer to do things
I'm using AngularJS and Firebase and trying to get the first child from a filtered set of children but limitToFirst(1) doesn't seem to get the first child like .child("=KDhddgd47nd") does
Like this
var Sport = new Firebase(FirebaseUrl);
var Teams = Sport.child("teams");
var myTeam = Teams.child("Saints");
var myPlayers = myTeam.child("players").orderByChild("name");
var myFixtures = myTeam.child("fixtures").startAt(now).orderByChild("date");
So I have a collection of fixtures now (myFixtures)
*var myFirstFixture = myFixtures.child("-KDUNN5KRNUmLlOhUB4D");*
works and gets the fixture where -KDUNN5KRNUmLlOhUB4D = the id of the fixture
but
var myFirstFixture = myFixtures.limitToFirst(1);
does not get the same result, ie. doesn't get a fixture at all
It should though shouldn't it?
Hmm... Im preety sure you have to attach a call-back as this doc refers to.. May you try doing this and updating us with results?
var myFirstFixture = myFixtures.limitToFirst(1).on("child_added", function(snapshot) {
console.log(snapshot.key() , snapshot.val());
});
An educated guess is that you're using:
$scope.fixture = $firebaseObject(myFirstFixture);
This will work when you have a direct Firebase reference to that first fixture, as when you do myFixtures.child("-KDUNN5KRNUmLlOhUB4D").
It will however not work when you use a query. Since there may be multiple items that match your conditions, a query will always return a list of items. Even when there is only one matching fixture, the query will still result in a list of one fixture. So you'll need to map it to an array:
$scope.fixtures = $firebaseArray(myFirstFixture);
And then ng-repeat over it in your view HTML.
In my cloud code I want to retrieve the first object in the "Messages" class. Then i want to grab some information from that object, send it to another class, and finally delete that object from the "Messages" class i originally pulled it from.
My question is do i need to query the entire "Messages" class just to get the first object in it? I don't want to slow down my app due to inefficient code.
Parse.Cloud.afterSave("sendMessage", function(Parse.Message, response) {
var body = null;
var senderName = null;
var senderId = null;
var randUsers = [];
var query = new.Parse.Query(Parse.Message);
query.find({
success: function(results){
body.push(results[1].get("messageBody"));
senderName.push(results[1].get("senderName"));
senderId.push(results[1].get("senderId"));
response.success(getUsers);
},
error: funtion(error){
response.error("Error");
}
});
});
to avoid confusion: "getUsers" is an arbitrary function call.
To retrieve entry from class, you need the query the table. However, your problem is getting the first record which does not require getting the all record. From your code I can see that you get the first record of result array (result[1] ). You can apply the solution; getting the first record of the class that you want to query. You can do it via two ways; either you can set the limit 1 to your query or you can use the first() method. The Parse.Query JS API link is below;
https://parse.com/docs/js/symbols/Parse.Query.html
Check the limit and first methods.
Hope this helps.
Regards.