Firebase - Data structure issue for extracting an object from nested structure - javascript

Firebase - Data structure issue for extracting an object from nested structure.
I want to find the uid and then check if the key is a jobId.
I've labelled accordingly below.
I'm using typescript and angular2 with firebase.
This is my current attempt that returns "null":
var jobId = "-K5fIAiuHM-4xeEQJiIS";
var uid = "3f61ae7a-99a1-4cbf-9c8e-00b2249956a7";
var userRef = this.refApp.child('key').child(uid);
var query = userRef.child('jobId').child(jobId);
query.on('value', (snap) => {
//This returns null
var response = snap.val();
});
This is my database structure:

Your structure is /applications/$userId/$jobId. Use those keys to get to your data.
JSBin Demo
var jobId = "-K5fIAiuHM-4xeEQJiIS";
var uid = "3f61ae7a-99a1-4cbf-9c8e-00b2249956a7";
var refApp = new Firebase('<my-firebase-app>/applications');
var jobRef = refApp.child(uid).child(jobId);
jobRef.on('value', (snap) => console.log(snap.val()));
Right now you're using "key", which I believe is from my previous demo. That's just for show, not for your actual solution. Keep your data structure in mind when reading the sample code, because it can vary.

Related

How to getting values ​with multiple key queries in IndexedDb

I created an ObjectStore named "components" with the code below.
var objectStore = db.createObjectStore("components", { keyPath: "id", autoIncrement: true });
let index = objectStore.createIndex('componentFloorId, componentRoomId', ['componentFloorId', 'componentRoomId']);
The view of the data in the browser
Using the componentFloorId and componentRoomId Keys, I can query with the code below.
const txn = db.transaction('components', 'readonly');
const store = txn.objectStore('components');
// get the index from the Object Store
const index = store.index('componentFloorId, componentRoomId');
// query by indexes
let query = index.getAll([floorIdFromCard, roomIdFromCard]);
However, what I need is to be able to query with the id key as well as these two keys.
SQL Query Example
SELECT * FROM components WHERE componentFloorId="1" AND componentRoomId="1" AND id=2;
How do I do this sql query with indexeddb?

How can I get the last object in this JSON array?

I'm trying to use player data from a football stats API, but I can't seem to get data for the current season (which can be found in the last object in the array). For some reason I'm only getting data for the third index (code below).
.then(data => {
//BIO
const bio = data['data'][0]
const nameValue = bio['fullname']
const imageValue = bio['image_path']
const teamValue = bio['team']['data']['name']
const countryValue = bio['nationality']
const birthdateValue = bio['birthdate']
const heightValue = bio['height']
const positionValue = bio['position']['data']['name']
//STATS
const stats = bio['stats']['data']['data'.length - 1]
const appearancesValue = stats['appearences']
Here is an image of the JSON data I am trying to access. In this instance I should be getting data from [4] but I'm getting it from [3].
I'm quite inexperienced so I feel like I must be making a silly mistake somewhere! Appreciate any help.
the 'data'.length in the bio['stats']['data']['data'.length - 1] part will evaluate to the length of the "data" string. so it is always 4.
You most likely wanted the length of the array so it should be
bio['stats']['data'][bio['stats']['data'].length - 1]
Or you could extract it beforehand in a variable, for clarity
const dataLength = bio['stats']['data'].length;
const stats = bio['stats']['data'][dataLength - 1];
Also since you are using literals for the object properties you do not need to use the [] notation.
const dataLength = bio.stats.data.length;
const stats = bio.stats.data[dataLength - 1];
and you can do that with the rest of the code as well, to avoid typing all the ['..']
Building up on Henry Walker's answer.
Using the new JavaScript Array.at() method allows you to enter both positive and negative indices.
This code:
const dataLength = bio.stats.data.length;
const stats = bio.stats.data[dataLength - 1];
Would simply translate to:
const stats = bio.stats.data.at(-1);
Giving you the last element in the array.
As data object signifies, it has 5 objects in it, you can this particular object at 3rd place as in an array 1st value is stored at index 0. Try using this code to fetch the last object
var lastObject = bio.stats.data[bio.stats.data.length-1].player_id

filter fire-base keys with given value

I have a fire base data structured like this:
I want to list all the keys under candidate_employer that start with for example "5_" using JavaScript
Something like this should work:
let root = firebase.database().ref();
let ref = root.child("chat/candidate_employer");
let query = ref.orderByKey().startAt("5_").endAt("5~");
query.once("value").then(function(results) {
results.forEach(function(snapshot) {
console.log(snapshot.key);
})
})
Also see the Firebase documentation on ordering and filtering data.

Storing Objects in LocalStorage with VUE.js

I need to store an Object called Projects that contains Teams and each Team contains users, all that without tables or other sql stuff, all in localstorage, and after I need to CRUD them and all that stuff. Any Ideas?
project = JSON.parse(localStorage.getItem('projects'));
console.log(project);
project.push(this.projectname);
localStorage.setItem("projects",JSON.stringify(project));
You could use an array of objects, something like below :
var user1 = {"name":"user1"}; //Object1
var user2 = {"name":"user2"}; //Object2
var team = []; //array of objects
team.push(user1);
team.push(user2);
var projects = [];
projects.push(team);
console.log(projects); //store this into localstorage

Firebase Sorting Data Retrieval

This is the code that I have: I am trying to get data stored in the Firebase Database sorted by wage. The order of the database goes: "Posts -> PostID(.push when saving) -> Wage." I have the data retrieval working just not in order.
var PostsRef = firebase.database().ref().child("Posts");
PostsRef.on('child_added', function(data) {
var title = data.val().title;
var description = data.val().description;
var completionDate = data.val().completionDate;
var complexity = data.val().complexity;
var wage = data.val().wage;
var uid = data.val().userID;
});
You're storing the wages as string, which means that they will be sorted in lexicographical order:
1
13
2
20
3
If you want to get the results in numerical order, you should store the wages as numbers, so without the quotes.
If you store them from your code, this might require that you convert it with parseInt(wagesAsString).
After you store the wages as numbers, you can get them in order with:
var PostsRef = firebase.database().ref().child("Posts");
var query = PostsRef.orderByChild("wage");
query.on('child_added', function(data) {

Categories

Resources