Firebase (nosql) checking if key contains substring - javascript

So after building a chat app with angularjs and PHP I realized it was horrible for server performance and decided to give firebase a try using angularjs to talk with firebase(angularfire) right now I have hit a little roadblock and can't seem to figure out how to accomplish displaying a users chat rooms he's apart of. Please note this is my FIRST time using NoSql structure.
Currently my structure is like so:
{
"-K4KXS4k3mftFMe7jy_g" : {
"members" : {
"guest:Aaaa1aa" : {
"user1" : "Aaaa1aa",
"user2" : "guest"
}
},
"messages" : {
"guest:Aaaa1aa" : {
"-K4LdBwkMe7dcshqCXxW" : {
"content" : "gg",
"from" : "Aaaa1aa"
}
}
},
"rooms" : {
"guest:Aaaa1aa" : {
"roomname" : "guestAaaa1aa",
"type" : "private"
}
}
}
}
I want to check if
members->'key'->user1 == 'Aaaa1aa'
but the way I construct the key for each members data(from room key) is passed two parameters when the user clicks on 'message'(creates new room or opens existing room) in another function and that is their user name and the users profile name they clicked on. hence the keys with the delimiter ':' (guest:Aaaa1aa).
So my question is can I check if the members key contains a substring value ? sort of like explode in PHP.
What I want my query to be like:
select uniqueid(room_name) from members where user1 = 'passed value'
and if above is possible would the below be possible as well ?
select uniqueid(room_name) from members where user1 = 'passed value' || user2 = 'passed value'
thanks for any help, if I am structuring this wrong please let me know and point me into the right direction.

Related

Retrieve data from Firebase using Google Apps Script

I'm developing a Google Spreadsheet to manage reservations for a hotel. It has two main tabs. One of them is used to make the reservations and the other one is used to make queries to the reservations already made. I managed to make it work just fine with the built-in tools of google apps script using a tab as database.
I'm trying to export my data to a Firebase database, but I cannot find how to fetch some information I need. My data is stored using a code generated using the date of the reservation as integer format + the name of the person without spaces. This is the JSON generated by firebase:
{
"44256001LarissaMeimbergBaraldi" : {
"code" : 44256001,
"date" : "2021-03-01T03:00:00.000Z",
"name" : "Larissa Meimberg Baraldi"
},
"44256001ÍcaroNovodeOliveira" : {
"code" : 44256001,
"date" : "2021-03-01T03:00:00.000Z",
"name" : "Ícaro Novo de Oliveira"
}
}
My question is: let's suppose I want to know all the reservations made for the day 01/March/2021, what is the code for me to look inside the objects and then, if they match my search, get the info I need?
I converted the JSON to an array of objects, then filtered by date. Added the console logs to check if everything is right. You can see the logs when you go to view -> executions in your script. Click on the function execution to see the logged objects.
function myFunction() {
var a ={
"44256001LarissaMeimbergBaraldi" : {
"code" : 44256001,
"date" : "2021-03-01T03:00:00.000Z",
"name" : "Larissa Meimberg Baraldi"
},
"44256001ÍcaroNovodeOliveira" : {
"code" : 44256001,
"date" : "2021-03-01T03:00:00.000Z",
"name" : "Ícaro Novo de Oliveira"
},
"44256002ÍcaroNovodeOliveira" : {
"code" : 44256002,
"date" : "2021-04-01T03:00:00.000Z",
"name" : "Ícaro Dovo de Oliveira"
}
};
var values_a = Object.values(a);
var keys_a = Object.keys(a);
var array_a = keys_a.map((item, index)=> {return {"key": item, "values": values_a[index]};});
console.log(array_a);
var filter_date = "2021-03-01T03:00:00.000Z";
var filtered_a=array_a.filter(item => {return item.values.date === filter_date;})
console.log(filtered_a);
}
Thank you for your help! But my point was actually a little bit different, maybe I wasn't so clear.
While trying to explain it to you, I found the answer to my question. It was right under my nose this whole time and I didn't notice it. Here is the solution I needed:
First, I have to assign a rule to my firebase telling it what element I will be working on, so if I want to find reservations based on the date, it would look like this:
{
"rules": {
".read": true,
".write": true,
".indexOn":["date"]
}
}
Then, back to my script, it will be like:
function getReservations() {
var ss = SpreadsheetApp.getActive().getSheetByName('Search');
var date = ss.getRange('C11').getValue();
var firebaseUrl = "https://script-examples.firebaseio.com/";
var base = FirebaseApp.getDatabaseByUrl(firebaseUrl);
var queryParameters = {orderBy:"date", equalTo: date};
var data = base.getData("", queryParameters);
for(var i in data) {
Logger.log(data[i].code, data[i].name, data[i].date);
}
}
The log retrieves:
[20-12-08 11:30:33:696 BRT] 44256001 Larissa Meimberg Baraldi 2021-03-01T03:00:00.000Z
[20-12-08 11:30:33:698 BRT] 44256001 Ícaro Novo de Oliveira 2021-03-01T03:00:00.000Z
This information was described on the documentation here:
https://sites.google.com/site/scriptsexamples/new-connectors-to-google-services/firebase/tutorials/read-and-write-data-in-firebase-from-apps-script
I think I got a little overwhelmed with the amount of information I got and skipped this part of the tutorial.
Thank you so much for your time and help.

How to filter and retrieve nested child in Firebase realtime database?

This is a simplified version of the DB structure that I'm working with:
"user" : {
"nhbAQ9p8BrMoAIbJNKvLlXTdiNz2" : {
"log" : {
"-LhMVugmjmIdqwrJSURp" : {
"a" : 25120,
"timeStamp" : 1560312000000,
},
"-Lh_Z9GsJJvlMOpVV9jU" : {
"a" : 19033,
"timeStamp" : 1564718400000,
}
}
}
}
I'm having issues filtering and retrieving the value of "a" with a given user id (e.g. nhbAQ9p8BrMoAIbJNKvLlXTdiNz2) and timeStamp (e.g.1560312000000).
I've tried combinations of orderByChild(), equalTo(), and adding a once() listener to do the task but they've only returned null so far.
The code that I have:
firebase.database().ref('user/' + userID + + '/log').orderByChild('timeStamp').equalTo(targetTimeStamp).once('value').then(function(snapshot){
let userLog = snapshot.val().a
})
where userID is a string and targetTimeStamp is a number.
I checked the doc and a post about orderByChild() but I'm still not sure what is causing it to return null.
This is my first time posting a question, please comment if there's anyway I can make this clearer and any help is much appreciated!
where userID and targetTimeStamp are both strings.
That is the reason nothing is returned. In the database the values of the timeStamp property is a number, and comparing a number to a string never returns a match.
To make the query work, convert the string to a number:
...equalTo(parseInt(targetTimeStamp)).once(...
Aside from that a query against the Firebase Database may potentially have multiple results. So the snapshot contains a list of those results. Even if there is only a single result, the snapshot will contain a list of one result.
So you need to handle that case too:
firebase.database().ref('user/' + userID + + '/log').orderByChild('timeStamp').equalTo(targetTimeStamp).once('value').then(function(results){
results.forEach(function(snapshot) {
let userLog = snapshot.val().a
})
})

How can I reformat this simple JSON so it doesn't catch "Circular structure to JSON" exception?

Introduction
I'm learning JavaScript on my own and JSON its something along the path. I'm working on a JavaScript WebScraper and I want, for now, load my results in JSON format.
I know I can use data base, server-client stuff, etc to work with data. But I want to take this approach as learning JSON and how to parse/create/format it's my main goal for today.
Explaining variables
As you may have guessed the data stored in the fore mentioned variables comes from an html file. So an example of the content in:
users[] -> "Egypt"
GDP[] -> "<td> $2,971</td>"
Regions[] -> "<td> Egypt </td>"
Align[] -> "<td> Eastern Bloc </td>"
Code
let countries = [];
for(let i = 0; i < users.length; i++)
{
countries.push( {
'country' : [{
'name' : users[i],
'GDP' : GDP[i],
'Region' : regions[i],
'Align' : align[i]
}]})
};
let obj_data = JSON.stringify(countries, null, 2);
fs.writeFileSync('countryballs.json', obj_data);
Code explanation
I have previously loaded into arrays (users, GDP, regionsm align) those store the data (String format) I had extracted from a website.
My idea was to then "dump" it into an object with which the stringify() function format would format it into JSON.
I have tested it without the loop (static data just for testing) and it works.
Type of error
let obj_data = JSON.stringify(countries, null, 2);
^
TypeError: Converting circular structure to JSON
--> starting at object with constructor 'Node'
| property 'children' -> object with constructor 'Array'
| index 0 -> object with constructor 'Node'
--- property 'parent' closes the circle
What I want from this question
I want to know what makes this JSON format "Circular" and how to make this code work for my goals.
Notes
I am working with Node.js and Visual Studio Code
EDIT
This is further explanation for those who were interested and thought it was not a good question.
Test code that works
let countries;
console.log(users.length)
for(let i = 0; i < users.length; i++)
{
countries = {
country : [
{
"name" : 'CountryTest'
}
]
}
};
let obj_data = JSON.stringify(countries, null, 2);
fs.writeFileSync('countryballs.json', obj_data);
});
Notice in comparison to the previous code, right now I am inputing "manually" the name of the country object.
This way absolutely works as you can see below:
Now, if I change 'CountryTest' to into a users[i] where I store country names (Forget about why countries are tagged users, it is out of the scope of this question)
It shows me the previous circular error.
A "Partial Solution" for this was to add +"" which, as I said, partially solved the problem as now there is not "Circular Error"
Example:
for(let i = 0; i < users.length; i++)
{
countries = {
country : [
{
"name" : users[i]+''
}
]
}
};
Resulting in:
Another bug, which I do not know why is that only shows 1 country when there are 32 in the array users[]
This makes me think that the answers provided are not correct so far.
Desired JSON format
{
"countries": {
"country": [
{
"name": "",
"GDP" : "",
"Region" : "",
"Align" : ""
},
{
"name": "",
"GDP" : "",
"Region" : "",
"Align" : ""
},
{
"name": "",
"GDP" : "",
"Region" : "",
"Align" : ""
}
]}
}
Circular structure error occurs when you have a property of the object which is the object itself directly (a -> a) or indirectly (a -> b -> a).
To avoid the error message, tell JSON.stringify what to do when it encounters a circular reference. For example, if you have a person pointing to another person ("parent"), which may (or may not) point to the original person, do the following:
JSON.stringify( that.person, function( key, value) {
if( key == 'parent') { return value.id;}
else {return value;}
})
The second parameter to stringify is a filter function. Here it simply converts the referred object to its ID, but you are free to do whatever you like to break the circular reference.
You can test the above code with the following:
function Person( params) {
this.id = params['id'];
this.name = params['name'];
this.father = null;
this.fingers = [];
// etc.
}
var me = new Person({ id: 1, name: 'Luke'});
var him = new Person( { id:2, name: 'Darth Vader'});
me.father = him;
JSON.stringify(me); // so far so good
him.father = me; // time travel assumed :-)
JSON.stringify(me); // "TypeError: Converting circular structure to JSON"
// But this should do the job:
JSON.stringify(me, function( key, value) {
if(key == 'father') {
return value.id;
} else {
return value;
};
})
The answer is from StackOverflow question,
Stringify (convert to JSON) a JavaScript object with circular reference
From your output, it looks as though users is a list of DOM nodes. Rather than referring to these directly (where there are all sort of possible cyclical structures), if you just want their text, instead of using users directly, try something like
country : [
{
"name" : users[i].textContent // maybe also followed by `.trim()
}
]
Or you could do this up front to your whole list:
const usersText = [...users].map(node => node.textContent)
and then use usersText in place of users as you build your object.
If GDP, regions and align are also references to your HTML, then you might have to do the same with them.
EUREKA!
As some of you have mentioned above, let me tell you it is not a problem of circularity, at first..., in the JSON design. It is an error of the data itself.
When I scraped the data it came in html format i.e <td>whatever</td>, I did not care about that as I could simply take it away later. I was way too focused in having the JSON well formatted and learning.
As #VLAZ and #Scott Sauyezt mentioned above, it could be that some of the data, if it is not well formatted into string, it might be referring to itself somehow as so I started to work on that.
Lets have a look at this assumption...
To extract the data I used the cheerio.js which gives you a kind of jquery thing to parse html.
To extract the name of the country I used:
nullTest = ($('table').eq(2).find('tr').eq(i).find('td').find('a').last());
//"Partial solution" for the OutOfIndex nulls
if (nullTest != null)
{
users.push(nullTest);
}
(nullTest helps me avoid nulls, I will implement some RegEx when everything works to polish the code a bit)
This "query" would output me something like:
whatEverIsInHereIfThereIsAny
or else.
to get rid off this html thing just add .html() at the end of the "jquery" such as:
($('table').eq(2).find('tr').eq(i).find('td').find('a').last().html());
That way you are now working with String and avoiding any error and thus solves this question.

How do I to target a single value in firebase database?

I'm having trouble figuring out how to target a single object in the firebase database. For example, I want to have a specific word/definition shown when I click an index card. I'm using this to store the data:
wordVal = $("#word").val();
defVal = $("#def").val();
data = firebase.database().ref("indexCards");
data.push( { 'word': wordVal, 'definition': defVal } );
and this to retrieve it:
data.on("child_added", function(snapshot){
console.log(snapshot.val().word);
console.log(snapshot.val().definition);
});
This gives me the whole list of words and definitions. I want to refer to specific words and specific definitions, separately. The docs say that I can reference the specific values by doing this - firebase.database().ref("child/path").
But my question is...how can I reference the path when the parents are those random numbers and letters (see below)? I know that these are unique IDs generated by firebase, but I don't know how to access them like I'd access ordinary objects.
{
"-KQIOHLNsruyrrnAhqis" : {
"definition" : "person, place, thing",
"word" : "noun"
},
"-KQIOO7Wtp2d5v2VorqL" : {
"definition" : "device for photos",
"word" : "camera"
},
"-KQISp4WMnjABxQayToD" : {
"definition" : "circus act",
"word" : "clown"
},
"-KQITC9W1lapBkMyiL7n" : {
"definition" : "device used for cutting",
"word" : "scissors"
}
}
You can use a query like this:
data = firebase.database().ref('indexCards').orderByChild('word').equalTo('noun')
It is self-explanatory, we get reference to indexCards where value of key word is equal noun, so it will return object with key -KQHZ3xCHTQjuTvonSwj
Link to Firebase docs: Retrieve data - Sorting and Filtering data
You need to put the initial push into an object then call the object later. ie
To PUSH data:
firebase.database().ref().push( { 'word': wordVal, 'definition': defVal } )
To UPDATE data or call it later:
firebase.database().ref("indexCards").set({})
or in this case:
data.set({})

MongoDB, PHP and JavaScript

I have the following document in a MongoDB 2.0.4 and PHP 5.5*
{
"children" : [
{
"name" : "openGL::gl"
},
{
"name" : "openGL::interfaces"
},
{
"name" : "openGL::picking"
},
{
"name" : "openGL::objects"
}
],
"name" : "test"
}
Using php I want to create another collection having a copy of this document.Because I cannot use php mongo::command I am just getting a cursor for the first collection and insert this cursor into the second:
$cursor = $collection->find();
foreach($cursor as $document){
$result->insert($document);
};
$collection is the original and $result is the new one.
Now the strange thing is sometimes this works perfectly and sometimes I recieve the following:
{
"children" : {
"3" : {
"name" : "openGL::objects"
},
"0" : {
"name" : "openGL::gl"
},
"1" : {
"name" : "openGL::interfaces"
},
"2" : {
"name" : "openGL::picking"
}
},
"name" : "test"
}
And this is really bad because I am trying to get those infos into Javascript and therefore the first one (the original) is an Array whereas the second one is an object with properties.
Does somebody know why I get this and how to fix it?
So this is the solution I am using now!
$db->command(array(
"eval" => new MongoCode("function(){
db['".$toCopy."'].copyTo('".$newName."')
};"
)
));
You can copy a collection on the server with the .copyTo() method for the collection:
db.collection.copyTo("new")
There is no client transfer as there is currently being done by iterating.
If for some reason you want this to be a part of your code then there is the "runCommand" option which has a longer syntax. So in PHP code, do the longer version of this with "eval":
$db->command(array(
"eval" => new MongoCode("function(){ " .
"db.collection.find().forEach(function(doc) { " .
"db.newcollection.insert(doc); " .
"}); " .
"};"
);
));
That will run the copy on the server. Take care to read the documentation and warnings on db.eval(). And aside from all else, but much the same as you were doing, then you must re-create all indexes on the target collection that you want to use.
But in general this will be a better way than iterating over a client connection.
Have you tried to sort the cursor like:
$cursor = $collection->find();
$cursor = $cursor->sort(array('name_of_key_variable' => 1)); //sorts in ascending order
foreach($cursor as $doc) {
...
}
You might also try more of the MongoCursor options listed here:
http://www.php.net/manual/en/class.mongocursor.php at the table of contents

Categories

Resources