I have this database:
{
"interpreters" : [ null, {
"InterpreterID" : "1",
"Name" : "Pedro",
"languages" : [ "portuguese", "russian", "english", "german" ],
"latitude" : 37.633,
"latitudeDelta" : 0.0143,
"longitude" : -122.345,
"longitudeDelta" : 0.0134
}, {
"InterpreterID" : "2",
"Name" : "Paulo",
"languages" : [ "english", "portuguese" ],
"latitude" : 37.554,
"latitudeDelta" : 0.0143,
"longitude" : -122.245,
"longitudeDelta" : 0.0134
} ]
}
And I'm trying to get only interpreters that match with the language I want. For example, get only interpreters
that speak russian.
I'm doing like this:
database()
.ref()
.child('interpreters')
.orderByChild('languages')
.equalTo('russian')
.on('value', snapshot => {
setInterpreters(snapshot.val())
console.log(snapshot.val())
});
But it returns 'null'.
If I look for orderByChild('Name').equalTo('Pedro') then return Pedros data.
Maybe it's because languages is an array but I'm not sure how to get data from it and couldn't find how to do it.
The forEach method simple didn’t work without any error. The code ran fine but I couldn’t display anything.
I'm following firebase documentation and seems that there is nothing different.
What should I do ?
Thank you in advance.
Firebase doesn't natively support arrays, well it does in form of objects. An array that you send as
["Portuguese", "Russian"]
is converted to
{0: "Portuguese", 1: "Russian"}
Hence your queries don't work as expected. Firebase doesn't support querying inner values of arrays
The workaround
Firebase recommends changing your data to:
{
"portugese": true,
"russian": true
}
and then query as
.orderByChild('languages/portuguese')
.equalTo(true)
Related
I'm building my first web app with React, Redux and Firebase, it's about registering the assistance of students (alumnos) to lessons (clases). I've the following database structure (the same in Redux state, this.props).
"clases" : {
"-LpQkLyGXEd-Up8hExTx" : {
"alumnos" : [ "-LpKkSh0E5jiuM0JCCpS", "-LpQi33M-0OSS4Jvup8k" ],
"fechaClase" : "20-09-2019",
"profesor" : "Nacho",
"tema" : "Misión"
},
"-LpQmExVsWtW1uPHLK52" : {
"alumnos" : [ "-LpJvbXb2FjgZvvBv3ei", "-LpKkSh0E5jiuM0JCCpS", "-LpQi33M-0OSS4Jvup8k", "-LpQiDGlRWITax2t6U2A" ],
"fechaClase" : "22-09-2019",
"profesor" : "Nacho",
"tema" : "Bautismo"
},
"-LpQqZ_uWu8HxROagVjN" : {
"alumnos" : [ "-LpKkSh0E5jiuM0JCCpS", "-LpQi33M-0OSS4Jvup8k", "-LpQiPCS2cIK7opMNqyH" ],
"fechaClase" : "21-09-2019",
"profesor" : "Manzo, Ignacio",
"tema" : "Bautismo"
}
I want to select a student (alumno), and know which lessons have made. Do I have to make a double map to the object? Can you give some help?
This is the deployed app https://metanoia-ic.herokuapp.com/
This is my github repository: https://github.com/tonicanada/metanoia
Thanks!
I would use Object.keys to be able to use filter and include Array.prototype methods. Asuming that clases is the object containing all the state, I would do something like this:
const studentId = this.props.studentId; // or any other value
const clasesPerStudent = Object.keys(clases).filter(clase =>
clases[clase].alumnos.includes(studentId)
);
I'm trying to get started with Firebase and I just want to make sure that this data structure is optimized for Firebase.
The conversation object/tree/whatever looks like this:
conversations: {
"-JRHTHaKuITFIhnj02kE": {
user_one_id: "054bd9ea-5e05-442b-a03d-4ff8e763030b",
user_two_id: "0b1b89b7-2580-4d39-ae6e-22ba6773e004",
user_one_name: "Christina",
user_two_name: "Conor",
user_one_typing: false,
user_two_typing: false,
last_message_text: "Hey girl, what are you doing?",
last_message_type: "TEXT",
last_message_date: 0
}
}
and the messages object looks like so:
messages: {
"-JRHTHaKuITFIhnj02kE": {
conversation: "-JRHTHaKuITFIhnj02kE",
sender: "054bd9ea-5e05-442b-a03d-4ff8e763030b",
message: "Hey girl, what are you doing?",
message_type: "TEXT",
message_date: 0
}
}
Is storing the name relative to the user in the conversation object needed, or can I easily look up the name of the user by the users UID on the fly? Other than the name question, is this good? I don't want to get started with a really bad data structure.
Note: Yes, i know the UID for the conversation & message are the same, I got tired of making up variables.
I usually model the data that I need to show in a single screen in a single location in the database. That makes it possible to retrieve that data with a single read/listener.
Following that train of thought it makes sense to keep the user name in the conversation node. In fact, I usually keep the username in each message node too. The latter prevents the need for a lookup, although in this case I might be expanding the data model a bit far for the sake of keep the code as simple as possible.
For the naming of the chat: if this is a fairly standard chat app, then user may expect to have a persistent 1:1 chat with each other, so that every time you and I chat, we end up in the same room. A good approach for accomplishing that in the data model, can be found in this answer: Best way to manage Chat channels in Firebase
I don't think you structured it right. You should bare in mind "What if" complete analysis.
Though, I would recommend structuring it this way (I made it up for fun, not really tested in-terms of performance when getting a huge traffic. but you can always do denormalization to increase performance when needed):
{
"conversation-messages" : {
"--JpntMPN_iPC3pKDUX9Z" : {
"-Jpnjg_7eom7pMG6LDe1" : {
"message" : "hey! Who are you?",
"timestamp" : 1432165992987,
"type" : "text",
"userId" : "user:-Jpnjcdp6YXM0auS1BAT"
},
"-JpnjibdwWpf1k-zS3SD" : {
"message" : "Arya Stark. You?",
"timestamp" : 1432166001453,
"type" : "text",
"userId" : "user:-OuJffgdYY0jshTFD"
},
"-JpnkqRjkz5oT9sTrKYU" : {
"message" : "no one. a man has no name.",
"timestamp" : 1432166295571,
"type" : "text",
"userId" : "user:-Jpnjcdp6YXM0auS1BAT"
}
}
},
"conversations-metadata" : { // to show the conversation list from all users for each user
"-JpntMPN_iPC3pKDUX9Z" : {
"id": "-JpntMPN_iPC3pKDUX9Z",
"date":995043959933,
"lastMsg": "no one. a man has no name.",
"messages_id": "-JpntMPN_iPC3pKDUX9Z"
}
},
"users" : {
"user:-Jpnjcdp6YXM0auS1BAT" : {
"id" : "user:-Jpnjcdp6YXM0auS1BAT",
"name" : "many-faced foo",
"ProfileImg" : "...."
"conversations":{
"user:-Yabba_Dabba_Doo" : {
"conversation_id": "-JpntMPN_iPC3pKDUX9Z",
"read" : false
}
}
},
"user:-Yabba_Dabba_Doo" : {
"id" : "user:-Yabba_Dabba_Doo",
"name" : "Arya Stark",
"ProfileImg" : "...."
"conversations":{
"user:-Jpnjcdp6YXM0auS1BAT" : {
"conversation_id": "-JpntMPN_iPC3pKDUX9Z",
"read" : true
}
}
}
}
}
My doc:
"_id" : "bf63XML4bo6CrfP9A",
"comments" : [
{
"user" : "fzkhiAArD4mgAAjbL",
"comment" : "what the hell are you doing in there?",
"commentedAt" : 1422367883366
},
{
"user" : "fzkhiAArD4mgAAjbL",
"comment" : "tada tada",
"commentedAt" : 1422368379037
},
{
"user" : "fzkhiAArD4mgAAjbL",
"comment" : "la la la la la",
"commentedAt" : 1422368393536
},
{
"user" : "fzkhiAArD4mgAAjbL",
"comment" : "no no no",
"commentedAt" : 1422368409692
}
],
"feed_id" : "ym8To4cdwwTcSczkS",
I want to send the recent 3 comments from this doc, how to do it?
I tried different things, nothing working
mycoll.find({_id:res._id},{fields:{sort: {commentedAt: 1}},fields: {comments:{$slice: 3}}});
FYO
I want this in publish funciton.
As far as I'm aware, you cannot sort the comments and then slice them, only slice them. If you really need to sort and slice, you should probably use a transform, although I think this would be computationally more expensive.
However, if you've $pushed comments onto the array chronologically you should be able to do (on the server only):
mycoll.find({_id:res._id},{fields: {comments:{$slice: -3}}});
to get the last 3.
Say you have exposed an API Product in Apigee. You would like to get a list of all the developers and their apps that have registered for the API Product.
There is a call to return those, documented here:
http://apigee.com/docs/api/get-list-keys-apps-developers-or-companies-api-product
But the IDs it returns appear to be useless. If you try developers, for instance:
https://api.enterprise.apigee.com/v1/organizations/YOUR-ORG/apiproducts/YOUR-PRODUCT?query=list&entity=developers
you get back a list of IDs. But to find which developer a given ID relates to is impossible, as the call to get a developer:
http://apigee.com/docs/api/get-developer
only accepts an email address.
How can I get a list of all the developers and their apps registered for a given API product?
The Apps a developer has is nested in each developer:
https://api.enterprise.apigee.com/v1/o/{your org}/developers
will return a list of developers like this:
["email#domain.com", "email2#domain2.com"]
Then you have to loop through each developer to get a list of their apps:
https://api.enterprise.apigee.com/v1/o/{your org}/developers/tesla#weathersample.com
Which gives you a bunch of meta data including apps:
{
"apps" : [ "weather" ],
"companies" : [ ],
"email" : "tesla#weathersample.com",
"developerId" : "Hk5mmLw9kKIM95qF",
"firstName" : "Nikolai",
"lastName" : "Tesla",
"userName" : "Nikolai",
"organizationName" : "jokeindex",
"status" : "active",
"attributes" : [ ],
"createdAt" : 1357858239543,
"createdBy" : "noreply_admin#apigee.com",
"lastModifiedAt" : 1357858239543,
"lastModifiedBy" : "noreply_admin#apigee.com"
}
Finally, if you look at each app you can see the products associated with that developer app:
https://api.enterprise.apigee.com/v1/o/{your org}/developers/tesla#weathersample.com/apps/weather
Gets you this detail:
{
"accessType" : "read",
"appFamily" : "default",
"appId" : "030fdcea-cf97-40b1-96df-12084aea513c",
"attributes" : [ {
"name" : "Developer",
"value" : "tesla#weathersample.com"
}, {
"name" : "DisplayName",
"value" : "Weather"
}, {
"name" : "Notes",
"value" : "not yet"
}, {
"name" : "lastModifier",
"value" : ""
} ],
"callbackUrl" : "http://example.com/callback",
"createdAt" : 1363578857830,
"createdBy" : "adminui#apigee.com",
"credentials" : [ {
"apiProducts" : [ {
"apiproduct" : "weather",
"status" : "approved"
} ],
"attributes" : [ ],
"consumerKey" : "{key}",
"consumerSecret" : "{key}",
"expiresAt" : -1,
"scopes" : [ ],
"status" : "approved"
} ],
"developerId" : "Hk5mmLw9kKIM95qF",
"lastModifiedAt" : 1386042817268,
"lastModifiedBy" : "michael.bissell#apigee.com",
"name" : "weather",
"scopes" : [ ],
"status" : "approved"
}
Take a look at the Org Snapshot Tool on git if you want to interrogate the entire org with one script:
https://github.com/apigee/api-platform-samples/tree/master/tools
This will interrogate every developer and every app and put it into a nice tree structure in your file system for future reference.
I have Postcode in my large database, which contains values like SL5 9JH, LU1 3TQ etc.
Now when I am pasting above postcode to maps.google.com it's pointing to a perfect location..
My requirement is like I want to pass post codes to maps.google.com and it should return a related latitude and longitude of that pointed location, that I want to store in my database.
So, most probably there should be some javascript for that... If anybody have another idea regarding that please provide it..
Thanks in advance...
A quick note for those finding this SO answer. The answer by Daniel Vassallo uses the Google Geocoding API V2 which has now been deprecated. The new v3 API uses a request format like this:
http://maps.googleapis.com/maps/api/geocode/output?parameters
An example for a postcode lookup, returning the data in JSON format is:
http://maps.googleapis.com/maps/api/geocode/json?address=SL59JH,+UK&sensor=false
This returns a JSON array that includes the lat and long in results->geometry->location->lat and results->geometry->location->lng
Example response:
{
"results" : [
{
"address_components" : [
{
"long_name" : "SL5 9JH",
"short_name" : "SL5 9JH",
"types" : [ "postal_code" ]
},
{
"long_name" : "Windsor and Maidenhead",
"short_name" : "Windsor and Maidenhead",
"types" : [ "administrative_area_level_2", "political" ]
},
{
"long_name" : "United Kingdom",
"short_name" : "GB",
"types" : [ "country", "political" ]
},
{
"long_name" : "Ascot",
"short_name" : "Ascot",
"types" : [ "postal_town" ]
}
],
"formatted_address" : "Ascot, Windsor and Maidenhead SL5 9JH, UK",
"geometry" : {
"bounds" : {
"northeast" : {
"lat" : 51.39655490000001,
"lng" : -0.66024660
},
"southwest" : {
"lat" : 51.39457330,
"lng" : -0.6624574999999999
}
},
"location" : {
"lat" : 51.39539040,
"lng" : -0.66096740
},
"location_type" : "APPROXIMATE",
"viewport" : {
"northeast" : {
"lat" : 51.39691308029150,
"lng" : -0.6600030697084980
},
"southwest" : {
"lat" : 51.39421511970851,
"lng" : -0.6627010302915021
}
}
},
"types" : [ "postal_code" ]
}
],
"status" : "OK"
}
The API spec is available here: https://developers.google.com/maps/documentation/geocoding/
The technical term for the process you describe is called reverse geocoding. Google offers the The Google Geocoding Web Service New working Google Geocoding Link, where you can do reverse geocoding on the server side, instead of in JavaScript on the client-side.
For example, if you try the following URLs in your browser, you would get back the latitude and longitude of the postcode passed in the q parameter, in CSV format:
http://maps.google.com/maps/geo?q=SL59JH,+UK&output=csv&sensor=false
http://maps.google.com/maps/geo?q=LU13TQ,+UK&output=csv&sensor=false
This is how you would be able to reverse geocode your postcodes in php, for example:
$url = 'http://maps.google.com/maps/geo?q=SL59JH,+UK&output=csv&sensor=false';
$data = #file_get_contents($url);
$result = explode(",", $data);
echo $result[0]; // status code
echo $result[1]; // accuracy
echo $result[2]; // latitude
echo $result[3]; // longitude
Note that as Pekka suggested in another answer, the Google Maps API Terms of Use seem to prohibit the storage of the results, unless the store acts as a cache for data that will used in Google Maps. You may want to get in touch with Google and enquire on the Google Maps API Premier to have more flexible terms of use for your geocoding requirements.
The Ordnance Survey have released the postcode locations on a Creative Commons licence (CC-BY v3, IIRC). It would be a lot less hassle (and a lot clearer legally) to use that instead.
There's even a version with WGS84 (a.k.a. GPS) coordinates mirrored by mySociety
The Google Geocoding API does that, although if I remember correctly, their terms of service forbid local storage of the geocoding results.
I know this is an old question, but just chipping in here with how I managed to achieve the same thing (in PHP, but should be fairly simple):
I had a database of thousands of differently formatted postcodes. I cleaned each and every one of them up, uniformly, with this function and batch updates:
function clean_postcode($postcode)
{
$out = preg_replace("/[^a-zA-Z0-9]/", '',strtoupper($postcode));
if(strlen($out)>3)
{
$out = substr($out, 0, (strlen($out) -3)).' '.substr($out, -3);
}
return $out;
}
Now that all postcodes are formatted uniformly, I downloaded and imported the Ordnance Survey's Code-Point data set (free) - https://www.ordnancesurvey.co.uk/opendatadownload/products.html
I imported all their CSVs into my database in a separate codepoint table. From each CSV I imported the postcode, and the Eastings and Northings values.
I ran the clean_postcode() function again in batch on all the Ordnance Survey data in my DB. About 50% of the postcodes have spaces in, and 50% don't - after this they were uniformly set.
I ran the following PHP script on each and every postcode in the codepoint table and saved the Latitude and Longitude values returned into this table: http://bramp.net/blog/os-easting-northing-to-lat-long
All done! You can now match up and pull a Lat/Lon value based on well-formatted postcodes.
Further reading: http://www.deepbluesky.com/blog/-/converting-os-coodinates-into-longitude-latitude_7/
Check out ALgolia places here. Super fast, Open source and MIT