Firebase getting the reference - javascript

The full path for my reference looks like this
data/-KdWI6HAF0_wh9-NTEpe/films/thelobster/rating
and I can set it with
firebase.database().ref('data/-KdWI6HAF0_wh9-NTEpe/films/thelobster/rating')
.set(5);
The problem is that both the keys -KdWI6HAF0_wh9-NTEpe and thelobster are dynamic.
It makes it more difficult than it should be, is there any way to build this with just the -KdWI6HAF0_wh9-NTEpe key and make the film name a wildcard? Oris there a better way I am missing?

You can use Firebase's child() method:
firebase.database().ref('data').child(key).child('films').child(filmKey).child('rating').set(5);
Alternatively you can use ES6 string interpolation:
firebase.database().ref(`data/${key}/films/${filmKey}/rating`).set(5);

Firebase returns 'key' which is the id used to reference your object. Something like this.
var ref = firebase.database().ref("users/ada");
ref.once("value")
.then(function(snapshot) {
var key = snapshot.key; // "ada"
var childKey = snapshot.child("name/last").key; // "last"
});
You can read more about it here.
For 'thelobster', you can console.log() the data that comes from firebase, check the location of the dynamically changing 'thelobster', set it to a variable, and use the variable in your url.
Because I don't know how your incoming data looks like, I can't provide you with that code.

Related

Next Auth "useSession" syntax

I'm reading through the next-auth documentation, and I'm confused by the syntax for the useSession hook. Here's how it's used in the documentation
const { data: session, status } = useSession()
However, I don't understand why we're assigning session to data. Wouldn't we achieve the same result if we just did this:
const { data, status } = useSession()
I'm sure I'm missing something here, but I'm not sure what it is. Any help would be appreciated.
Thanks!
It's just a naming convention in the next-auth world to use the term 'session' when using useSession(), so it'd be similar to when using getSession(), where in both cases session object includes a user object and expires string.
So long story short you can assign it to whatever var name you want, or just directly use the data variable.

Destructuring an object from a dynamic string name

I got this config.json file :
"signs_table": {
"id_field": "dummy_id_field_name",
"prop" : "dummy_prop_name"
...
}
This file contains tons of configuration for huge amount of tables stored in a database. Every table has different field name but the configuration for my code is the same for each table (an Id field name, different property fields, but of course fields name changes from table to table).
So, in my code, I am getting a data object and I want to be able to destructs it to dynamically named properties (from the configuration) like so :
const { dummy_id_field_name, dummy_prop_name} = this.props.data
but this is hard coded way. I would like to load the named properties based on the configuration file.
something like :
const IdField = config.get("signs_table").id_field // this will retrieve the actual field name from config.json I want to be able to pass it through the destructuring operation
const PropField = config.get("signs_table").prop
const { IdField , PropField } = data
Here the config.get("signs_table") line is a from a class method that manage my config.json file...it basically retrieves the property.
So far I found this usefull approach :
ES6 — How to destructure from an object with a string key?
But this does not help me since I need to first retrieve the field name from the configuration file...
Any Idea ?
You cannot avoid fetching the field names from the config files first:
const { id_field: IdField, pro: PropField } = config.get("signs_table"); // this will retrieve the actual field names from config.json
Then, afterwards you can use those as computed property names when destructuring your actual data:
const { [IdField]: idValue , [PropField]: propValue } = this.props.data;
console.log(idValue, propValue);
You can de-structure arbitrary property names as I'll show below, but the question is why are you forcing yourself into a syntax you are unfamiliar with. You should stick with the readable and straightforward approach instead of some fancy convoluted method.
const idField = config.get("signs_table").id_field; // this will retrieve the actual field name from config.json I want to be able to pass it through the destructuring operation
const propField = config.get("signs_table").prop;
const { [idField]: idValue, [propField]: propValue } = data;
It would be more straightforward to simply avoid the de-structuring altogether and access the fields directly.
const idField = config.get("signs_table").id_field; // this will retrieve the actual field name from config.json I want to be able to pass it through the destructuring operation
const propField = config.get("signs_table").prop;
const idValue = data[idField];
const propValue = data[propField];

Read/Write data in the child of a child Firebase HTML

Right now, I am able to write to my database like this:
var firebaseRef = firebase.database().ref();
firebaseRef.child(codeText).set(messageText);
and I can read data like this:
var firebaseReadRef = firebase.database().ref().child(child);
firebaseReadRef.on('value', function(datasnapshot){
var data = datasnapshot.val();
}
The problem is I can only store data like this http://i.imgur.com/hWfvUNE.png and I want to know how to store data like this http://i.imgur.com/Yui2wxp.png
firebaseRef.child(codeText).child("Child Name").set(messageText);
That way you get another child. You can also specify your reference like this:
firebase.database().ref("name/childName").set(messageText);
Hope it helped. You might want to check the documentation for more useful information.
https://firebase.google.com/docs/database/web/read-and-write

firebase cloud write data with a "key" paramter

I am learning Cloud Functions for Firebase. What I want is pass the key and value in the URL parameters, like:
https://xxx.cloudfunctions.net/addMessageSet?text=goodboy&key=testKey
And then in the Realtime Database set a testKey:goodboy.
I know use push() will generate a unique key (if i understood correctly) but I'd like use my own key each time. I am not sure if set() works.
My problem is push({originalKey:original}) doesn't work as expected. It writes:
originalKey: goodboy
Where originalKey is just key not the parameter from the URL. Is this possible or any other solutions?
The code is like below:
exports.addMessageSet = functions.https.onRequest((req, res) => {
// Grab the text parameter.
const original = req.query.text;
const originalKey = req.query.key;
admin.database().ref('/messages/').push({originalKey:original}).then(snapshot => {
console.log('goodboy', original, originalKey);
res.redirect(303, snapshot.ref);
});
});
If you want to use a key you're generating without firebase generating another you need to use set with your key in the path
admin.database().ref('/messages/' + originalKey).set(original).then(snapshot => { });
// if originalKey is not a string use String(originalKey)
You said about originalKey not beeing a url, but everything in firebase if url based, like this you're doing
myDB
|_ messages
|_ originalKey: original
and not
myDB > messages > originalKey > original
If you need another key after the messages node i recomend using a date UNIX number, momentJS is good to handle this.
Hope it helps
Using push() will indeed generate a unique key. You will need to use either set() or update().
Note that using set() will overwrite the data at the specified location including any child nodes.

Node.js: How can I get the reference for a Firebase Database Data Snapshot

I have a folder for each user. I have a DataSnapshot name "snapshot" that selects an item of the user that has been changed.
Using the following code, i get the snapshot for the item I want in the same user:
var locationSnapshot = snapshot.child("location");
This works. My question is how can I get the reference to this exact item in the database so that I can write it? Supposedly there is a function:
ref
non-null firebase.database.Reference
The Reference for the location that generated this DataSnapshot.
But when I use it, it doesn't work:
var locationReference = locationSnapshot.ref();
Question:
How do I use it or how do I get the reference?
In the latest Firebase SDK, ref is a property and not a function:
var locationReference = locationSnapshot.ref;

Categories