Firebase retrieves snapshot value as null - javascript

I use the .once( function in Firebase and am successfully retrieving the snapshot.key NAME of the directory. But this key has also a value.
When requesting snapshot.val() also gives out null despise it having a value.
The database looks like this:
stages {
stage1AVERYLONGHASH : "values i want to get"
stage2AVERYLONGHASH : "values i want to get"
}
My code
var ref = "stage1AVERYLONGHASH";
var branch = firebase.database().ref(ref).once('value').then(function(s){
console.log(s.key); // GIVES THE CORRECT ANSWER
console.log(s.val()); //GIVES null ... doesn't give me the "values i want.."
Am i doing it completely wrong?
I'm new to Firebase.
Please know that the database is structured like this intentionally.
I restricted read permission on "stages".
The game works as just requesting a hash from the database as a reference, to get contents.

I think you suppose to get the reference of the stage and then get the stage1 reference from him like :
.ref("stage").child("stage1")
I'm not sure about the actual syntax but I know that this is how I get my firebase data in android studio

Related

Stored procedure azure Cosmos DB returns empty collection

I tried to create a stored procedure using the sample sp creation code from Azure docs, but i couldn't fetch the collection details. It always returns null.
Stored Procedure
// SAMPLE STORED PROCEDURE
function sample(prefix) {
var collection = getContext().getCollection();
console.log(JSON.stringify(collection));
// Query documents and take 1st item.
var isAccepted = collection.queryDocuments(
collection.getSelfLink(),
'SELECT * FROM root r',
function (err, feed, options) {
if (err) throw err;
// Check the feed and if empty, set the body to 'no docs found',
// else take 1st element from feed
if (!feed || !feed.length) {
var response = getContext().getResponse();
response.setBody('no docs found');
}
else {
var response = getContext().getResponse();
var body = { prefix: prefix, feed: feed[0] };
response.setBody(JSON.stringify(body));
}
});
if (!isAccepted) throw new Error('The query was not accepted by the server.');
}
The console shows only this.
the results shows no doc found because of not getting collection.I have passed the partition key at time of execution via explorer.
I had a similar issue. I think the Azure portal doesn't execute stored procedures properly when the partition key is not a string.
In my case I had a partitionKey that is a number. When I executed the stored procedure via the portal I always got an empty resultSet, even though I had documents in my database. When I changed the structure a little, and made my partitionKey a string, the stored procedure worked fine.
Did you create the ToDoList Database with the Items Collection? Yo can do this from the Quick start blade in the Azure portal.
And then create an SP to run against that collection. There is no partition key required, so no additional params are required (leave blank).
The Collection is created without any documents. You may choose to add documents via the Query Explorer blade or via the sample ToDoList App that is available via the Quick start blade.
You are debugging in a wrong way.
It is perfectly fine to see "{\"spatial\":{}}" in your console log, even if the collection has items. Why? well because that is a property of that object.
So regarding what you said:
the results shows no doc found because of not getting collection
is false. I have the same console log text, but I have items in my collection.
I have 2 scenarios for why your stored procedure return no items:
I had the same issue trying on azure portal UI(in browser) and for my surprise I had to insert an item without the KEY in order that my stored procedure to see it.
On code you specify the partition as a string ie. new PartitionKey("/UserId") instead of your object ie. new PartitionKey(stock.UserId)

JavaScript (Discord) Is there a way for my bot to store values and then repeat?

I have my current Discord Bot project using JavaScript however i cannot find a way to store the value itself when done through a command such as !setname ___ hoping for a response of that being repeated back when I use !myname.
I know how to do it by storing it temporarily through:
bot.on('message', function (user, userID, channelID, message, evt) {
if(message == "!myname") {
bot.sendMessage({
to: channelID,
message: 'Your name is ' + user.username;
});
}
}
However i cant figure out how to do it through the ability to call for it whenever you want rather than getting an immediate response. For example setting my name now but being able to have it output when i use the command instead of having command that sets the value then outputs it in an immediate string
Would recommend a simple key-value dictionary style in the current instance.
(Though you could store it to a text-file or database later if you prefer the data to be persistent across different sessions.)
Instance based:
Based on this post on stackoverflow...
You can create a global dictionary at the top var usernameChangeDict = {};
Whenever the user invokes !setname, just do:
usernameChangeDict[user.id] = Their_new_name_here
Fetch it back using usernameChangeDict[user.id], should return null or empty if they did not set their name before.
Persistent data:
Could either store it in a text file on your local computer, or do a database as Zooly mentioned.(Though personally, a database would be an overkill if your bot is not going to be used by a wide range of people.)
Text file
Read from this post, it contains details on how to write onto a text file.
This post talks about reading from a text file.
I would recommend storing it in a JSON format to make your life easier, since JSON.parse exists.
Most likely you would end up storing in a format like this:
{ "23125167744": "someone", "USER_ID": "username" }
Access it by parsedJson["USER_ID"].
SQLite
This tutorial would probably explain how to set your SQLite for javascript better than I do.
Once its all setup, just store the userID and username, you can just do:
SELECT username FROM yourTable WHERE userID = ?;
and
INSERT INTO yourTable (username, userID) VALUES (?, ?);
For inserting and selecting into database respectively.

Pushing Elements to a JSON Array with Braces

I am having a hard time trying to push elements to a JSON file located in an external location; here's a backstory on what I am trying to achieve:
I am programming a private Discord bot and am currently working on the message-system portion of it. The whole idea is that a user's message is deleted if they aren't fully authorized onto the server; that user's message and UserID will be logged into the JSON file . The thing is, I can only log the message if a UserID is manually added to the array (using the push function, I can add the message). But, if I try to push a UserID to the file array, it acts as if the push function does not exist for this; I think the JSON is nested as well. I would appreciate any help I can get, thanks!
JSON
{"users":[{}]}
I want to put the UserID within the braces inside the brackets
Code to push to the JSON
function removeMessage(content, authorid) {
if (!messagedata.users[0][authorid]) {
messagedata.users[0].push(authorid);
}
}
Current I'm Getting:
TypeError: messagedata.users[0].push is not a function
Expected Output
{"users":[{"287423028147781654":["Hi"]}]}
The numerical value is the UserID, while 'Hi' is clearly the message
users[0] is an object, not an array (and hence has no push method). It appears you actually want to add a key to the object, so try this instead:
messagedata.users[0][authorid] = ["Hi"];

Need helping retrieving data from Firebase

So I've been using Firebase as a database for my website (this is a web based project, using HTML, CSS and JS) and I'm running into a problem retrieving data from it.
Basically this site allows users to create a profile for a character (they can fill in the name, the characters stats etc...) and when they click submit, it'll save the values they filled out to the database.
The values are saved perfectly fine, but when I go to retrieve the data the command doesn't seem to do anything.
So in order to get the profiles, I've been trying to use this bit of code to get whatever is stored at the specified .ref(path):
var uid = firebase.auth().currentUser.uid;
var getChar = firebase.database().ref('/users/' + uid + '/chars/').orderByKey();
Which according to the Firebase docs should return a list of keys at the path that I specified in .ref(). However whenever I try to access whatever is in the var, it just gives me the string that contains a link to the database that looks like this:
https://#mydatabaseurlhere.firebaseio.com/users/uid/chars
Where #mydatabaseurlhere is the url I created on the Firebase app, and the uid is the authenticated user's ID.
I've been reading the docs, and its telling me that the above code should return a list of whatever is at the path that I specified, but so far it just gives me a link. Is there something I've been missing from the Docs that'll allow me to access whatever data is currently in the database? Because I've tried to take a snapshot using .once() to no avail either. I've also set the rules on /users/ to allow anyone to read/write to the database but I'm still not able to access the data (or maybe I am accessing, I'm just missing how to retrieve it).
Either way, I'm wondering how one can go about accessing this data, as I'm extremely confused as to why I can't seem to retrieve the data that has been successfully written to the database.
You're defining a query. But that doesn't yet retrieve the data.
To retrieve the data, you need to attach a listener. For example:
var uid = firebase.auth().currentUser.uid;
var getChar = firebase.database().ref('/users/' + uid + '/chars/').orderByKey();
getChar.on('value', function(snapshot) {
snapshot.forEach(function(child) {
console.log(child.key, child.val());
});
});

how to update a Mongo.db collection in meteor.js?

I have a collection that I need to update when the user presses a button.
I just need to change one variable to another.
In the console, this line of code works:
db.users.update({username : "Jack"},{age : 13, username : "Jack"});
But when I put in this code:
Template.body.events({
'click #updateAge' = function() {
{
alert();
db.users.update({username : "Jack"},{age : 13, username : "Jack"});
}
}
})
into my JavaScript file for Meteor.js, it doesn't do anything at all (I don't get an error message, and I see the alert, but the update just doesn't work).
I've read through the Meteor Documentation on updating, but I just can't seem to get it to work.
Does anybody know what I'm doing wrong here?
Found the problem.
Since I defined my database in my lib.js file
users = new Meteor.collection("users");
I don't need to put a db in front of the db.users.update({_id : "Jack"},{...}). I also need to find the document using the given mongo _id, not the identifier "username".
so the appropriate code would be
users.update({_id : "Jack"},{$set:{age : 13, username : "Jack"}});
In mongodb, you will have to use an update operator(for ex: $set). Otherwise, your document will overwritten by the update object you are passing(I am not sure that's what you want). I think, its works same in meteor. So, you will have to do something like this:
Meteor.users.update({username : "Jack"},{$set: {age : 13}});
This might not be the problem as you've stated you do not get a error message but to be sure: have you already allowed the user to update documents in the user collection?
Something like:
(in collections/permissions.js)
user.allow({
update: function (userId) {
// the user must be logged in to allow updates
return (userId != null);
}
})

Categories