FireBase - angularfire setting object key as variable - javascript

I am using firebase(angularfire) in my angularjs app to store and process my message system but can't seem to figure out how to replicate the example data from the firebase docs
// room members are easily accessible (or restricted)
// we also store these by room ID
"members": {
// we'll talk about indices like this below
"one": {
"mchen": true,
"hmadi": true
}
}
Here the members.one contains the user name as a key and I am trying to do this for my data as well but can't seem to figure out a solution.
The members portion of my firebase data is like so:
members { one: { } }
I have two variables set in the $scope.
user_name = kep; //person chatting with name
sender_name = pek; //current user name
So I want to use the set function to insert data into members.one or in this case members.user_name + ':' + sender_name but where I am having trouble is how to actually insert the data without creating a parent object.
ref.child('members').child(user_name + ':' + sender_name).set({
user_name: true, sender_name: true
});
The problem arises when I try to pass user_name and sender_name into the set() function below is the result it gets.
members { "kep:pek": { user_name: true, sender_name: true }}
where as I want it to be:
members { "kep:pek": { kep: true, pek: true }}
If I put user_name and sender_name into an object and then run the set() function with the object passed it will create the following structure which is not what I am looking for:
members { "kep:pek": { newObject: { kep: true, pek: true }}}

Firebase team member here.
The Firebase Database is a just a JSON document.
So let's say you want to structure your data this way:
{
"members" : {
"kep:pek" : {
"kep" : true,
"pek" : true
}
}
}
A custom key is created by using the .child() method, or by creating a key in the JavaScript Object.
JSBin Demo
var rootRef = new Firebase('<my-firebase-app>');
var membersRef = rootRef.child('members');
var user_name = 'kep';
var sender_name = 'pek';
// child object to store custom keys
var objectToSave = {};
// set keys in [] syntax
objectToSave[user_name] = true;
objectToSave[sender_name] = true;
// use .child() with a formatted string to save the object
membersRef.child(user_name + ':' + sender_name).set(objectToSave);

Related

DynamoDB update with composite primary key with node sdk

I'm looking to use the update function part of the document client in the dynamoDB javascript SDK. My dynamoDB table has a primary partition key of "PK" (String) and a primary sort key "SK" (String). My understanding is this means my items need to be identified with their composite primary key which is some combination of "PK" and "SK"
I am using a single table design so an example item would look like
PK "CONTEST#2021"
SK: "POST#5673"
author: "USER#2759"
text: "Lorem ipsum"
commentNumber: 9
The logic of my code looks like this
const AWS = require('aws-sdk');
const dynamo = new AWS.DynamoDB.DocumentClient();
exports.addComment = async (event, context, callback) => {
const params = {
TableName: 'App',
Key: {
"PK": event.PK,
"SK": event.SK
},
UpdateExpression: 'set commentNumber = :number',
ExpressionAttributeValues: {
':number': event.updatedCommentCount
}
}
try {
var res = await dynamo.update(params).promise()
// handleSuccess(res)
} catch(err) {
// handleFail(err)
}
return 'success'
};
When I try the code above, i get an error saying the provided key element does not match the schema
I know there's something wrong with the Key key in my params, but the documentation isn't helping. It suggests it's possible to update with a composite key and seems to suggest that the value for Key can be an object with two keys, but this isn't working. How can I update my params to use the update function?
I believe you have to use # in front of attribute names like so: ...UpdateExpression: 'set #commentNumber = :number',...
So I had a similar issue and came across this thread. What ended up working for me is setting the Key attribute by first creating a key object and then assigning it to the update_parameter.
var update_params = {
TableName: 'App',
};
let key = {};
key.PK = event.PK;
key.SK = event.SK;
update_params.Key = key;
update_params.UpdateExpression = UpdateExpression;
update_params.ExpressionAttributeValues = ExpressionAttributeValues;

In Firebase when using push() How do I get the unique ID and store in my database [duplicate]

This question already has answers here:
When utilizing the .push method can I write a copy of the id to the object?
(2 answers)
Closed 7 months ago.
I am pushing data in firebase, but i want to store unique id in my database also .
can somebody tell me,how to push the data with unique id.
i am trying like this
writeUserData() {
var key= ref.push().key();
var newData={
id: key,
websiteName: this.webname.value,
username: this.username.value,
password : this.password.value,
websiteLink : this.weblink.value
}
firebase.database().ref().push(newData);
}
error is "ReferenceError: ref is not defined"
You can get the key by using the function key() of any ref object
There are two ways to invoke push in Firebase's JavaScript SDK.
using push(newObject). This will generate a new push id and write the data at the location with that id.
using push(). This will generate a new push id and return a reference to the location with that id. This is a pure client-side
operation.
Knowing #2, you can easily get a new push id client-side with:
var newKey = ref.push().key();
You can then use this key in your multi-location update.
https://stackoverflow.com/a/36774761/2305342
If you invoke the Firebase push() method without arguments it is a
pure client-side operation.
var newRef = ref.push(); // this does *not* call the server
You can then add the key() of the new ref to your item:
var newItem = {
name: 'anauleau'
id: newRef.key()
};
And write the item to the new location:
newRef.set(newItem);
https://stackoverflow.com/a/34437786/2305342
in your case :
writeUserData() {
var myRef = firebase.database().ref().push();
var key = myRef.key();
var newData={
id: key,
Website_Name: this.web_name.value,
Username: this.username.value,
Password : this.password.value,
website_link : this.web_link.value
}
myRef.push(newData);
}
Firebase v3 Saving Data
function writeNewPost(uid, username, picture, title, body) {
// A post entry.
var postData = {
author: username,
uid: uid,
body: body,
title: title,
starCount: 0,
authorPic: picture
};
// Get a key for a new Post.
var newPostKey = firebase.database().ref().child('posts').push().key;
// Write the new post's data simultaneously in the posts list and the user's post list.
var updates = {};
updates['/posts/' + newPostKey] = postData;
updates['/user-posts/' + uid + '/' + newPostKey] = postData;
return firebase.database().ref().update(updates);
}
You can get last inserted item id using Promise like this
let postRef = firebase.database().ref('/post');
postRef.push({ 'name': 'Test Value' })
.then(res => {
console.log(res.getKey()) // this will return you ID
})
.catch(error => console.log(error));
Try this . It worked for me
this.addressRef.push(addressObj).then(res => {
console.log("address key = " + res.key) ;
});
Here res.getKey() will not work but use res.key to get the latest push ID
It looks like now .push() always returns an Observable. When applied the solutions above I had the following error: "Type 'String' has no compatible call signatures".
That being said, I refer what did work in my case for this new version:
Type 'String' has no compatible call signatures
This worked for me:
var insertData = firebase.database().ref().push(newData);
var insertedKey = insertData.getKey(); // last inserted key
See Here: Saving data with firebase.

showing complete firebase json data on webpage

I'm using firebase to collect data, and i'd like to create a temporary webpage to quickly see the json database (and share it) while testing.
The data is grouped by a date string then the with a random key and then the data. Eg:
{
"20160304" : {
"-KC-aOwSWpt4dlYmjJE4" : {
"coordinates" : "-37.7811465912404, 145.005993055861",
"event" : "Test event",
"time" : "2016-03-04 07:48:43 +0000"
}, etc...
To test showing the event data I'm using javascript in the html as follows:
var myFirebaseRef = new Firebase("https://xxxx.firebaseio.com/");
myFirebaseRef.orderByKey().on("value", function(snapshot) {
snapshot.forEach(function(snapshot) {
console.log("The " + snapshot.key() + " event is " + snapshot.val().event);
});
});
But it only returns
The 20160304 event is undefined
The 20160305 event is undefined
Does anyone know how I can grab the event string?
You're trying to skip a level in your JSON:
<date>
<pushid>
coordinates: ...
event: ...
time: ...
Since you're listening on the root if this structure, your snapshot.forEach() loops over the dates. That means that you still need to loop over the push ids:
var myFirebaseRef = new Firebase("https://xxxx.firebaseio.com/");
myFirebaseRef.orderByKey().on("value", function(snapshot) {
snapshot.forEach(function(snapshot) {
var events = snapshot.val();
Object.keys(events).forEach(function(key) {
console.log(events[key]);
});
});
});
If on the other hand you only want to cater for one event per day, you should store them without the pushid level in there.

How to do dynamic queries on MySQL from Meteor?

I have been trying to make dynamic queries against MySQL from Meteor using the numtel:mysql package. So far it's not successful. Perhaps I either need to know how to pass a dynamic argument to the subscribe, or need to know how to get the result of liveDb.select as an array or object rather than a cursor (liveDb is instantiated by called new LiveMysql(...)). I have tried doing the query in a method on the server side (as declared in Meteor.methods(...), and the method does not return the result. If anyone has code examples for this, that would be very much appreciated!
Here is helpful links for use Meteor with MySQL for select query, execute stored procedure,user mongo like publish subscribe method as well as join query in publish.
MySql:numtel package
Leaderboard MySql example
// The below code reference from Leaderboard MySql example
Meteor.publish('allPlayers', function() {
return liveDb.select(
'SELECT * FROM players ORDER BY score DESC',
[ { table: 'players' } ]
);
});
Meteor.publish('playerScore', function(name) {
return liveDb.select(
'SELECT id, score FROM players WHERE name = ' + liveDb.db.escape(name),
[
{
table: 'players',
condition: function(row, newRow, rowDeleted) {
// newRow provided on UPDATE query events
return row.name === name || (newRow && newRow.name === name);
}
}
]
);
Meteor.methods({
'incScore': function(id, amount) {
check(id, Number);
check(amount, Number);
liveDb.db.query(
'UPDATE players SET score = score + ? WHERE id = ?', [ amount, id ]);
}
});
You need to call change on your MysqlSubscription with the same params as defined in the Meteor.publish.
In my case:
export const mySqlSubscription = new MysqlSubscription('tableName');
Meteor.publish('tableName', function(filters){
var filterString = buildFilterString(filters);
var qString = 'SELECT ..... FROM tableName '+filterString;
//console.log(qString);
return liveDb.select( qString, [ { table: 'tableName' } ] );
}
);
Then whenever I want to update my subscription for a different filter I call:
mySqlSubscription.change(this.getReactively('filterRecord'));

Firebase update or set

After adding a post about a person to a Firebase database, I want to add the reference to the new post to the person. However the person may or may not already exist.
I have:
var ref = new Firebase("https://mydatabase.firebaseio.com/");
var _person = document.getElementById("Person").value;
var _remark = document.getElementById("Remark").value;
var postsRef = ref.child("remarks");
var newPostRef = postsRef.push({
person: _person,
remark: _remark
});
var postID = newPostRef.key();
var personRef = ref.child("person");
personRef.update({
_person: postID
});
However that creates a node called _person in child person instead of the value of the _person variable. Using set() would overwrite an existing person.
Example:
First a node remarks/-JlkbxAKpQs50W7r84gf is created with child node person/123456
After that I want to create a node person/123456 (only if it doesn't already exist) and than add a child node remark/-JlkbxAKpQs50W7r84gf to it. The post-id is automatically generated (Firebase) but the person's id is to be taken from a html form.
How do I do that?
Depending on how your data is structured, before you update, you may be able to get a reference to the person you want.
So, if your data looks something like this:
{
"remarks" : {
...
},
"person" : {
"123456" : {
"name" : "foo",
...
"blah" : "bar"
},
...
}
}
And document.getElementById("Person").value gives you 123456, you can get the reference like:
var personRef = ref.child("person").child(_person);
Then you want to see if it exists, and if it does, update it:
personRef.once('value', function(snapshot) {
if( snapshot.val() === null ) {
/* does not exist */
} else {
snapshot.ref.update({"postID": postID});
}
});

Categories

Resources