Display relational data in Firebase using AngularJS - javascript

I want to display content using a flat relational data structure (similar to that of Firefeed). Everything is working the way it should, except I can't figure out how to display the actual content. I'm struggling for a while now and I think I'm almost there actually, but something is still missing.
I have two references:
var userFeedRef = new Firebase(FIREBASE_URL).child("users").child($rootScope.currentUser.$id).child("feed");
var uploadsRef = new Firebase(FIREBASE_URL).child("uploads");
The JSON looks like this:
{
"uploads" : {
"-KGkxzQj0FM2CMAXo5Em" : {
"author" : "87a8b6c8-7f72-45c2-a8c5-bb93fe9d320d",
"date" : 1462184179564,
"name" : "Zizazorro",
"reasonUpload" : "Test",
"startSec" : 80,
"uploadTitle" : "Kid Ink - Promise (Audio) ft. Fetty Wap"
},
"-KGlCoD7kEa1k3DaAtlG" : {
"author" : "87a8b6c8-7f72-45c2-a8c5-bb93fe9d320d",
"date" : 1462188328130,
"name" : "Zizazorro",
"reasonUpload" : "Test2",
"startSec" : 80,
"uploadTitle" : "Kid Ink - Show Me ft. Chris Brown"
}
},
"users" : {
"87a8b6c8-7f72-45c2-a8c5-bb93fe9d320d" : {
"date" : 1459369248532,
"feed" : {
"-KGkxzQj0FM2CMAXo5Em" : true,
"-KGlCoD7kEa1k3DaAtlG" : true
},
"firstname" : "Bob",
"followers" : {
"e3de536b-03a1-4fb4-b637-ebcebaae55c6" : true
},
"following" : {
"e3de536b-03a1-4fb4-b637-ebcebaae55c6" : true
},
"regUser" : "87a8b6c8-7f72-45c2-a8c5-bb93fe9d320d",
"uploads" : {
"-KGkxzQj0FM2CMAXo5Em" : true,
"-KGlCoD7kEa1k3DaAtlG" : true
},
"username" : "Zizazorro"
},
"e3de536b-03a1-4fb4-b637-ebcebaae55c6" : {
"date" : 1459369285026,
"feed" : {
"-KGkxzQj0FM2CMAXo5Em" : true,
"-KGlCoD7kEa1k3DaAtlG" : true
},
"firstname" : "Anna",
"followers" : {
"87a8b6c8-7f72-45c2-a8c5-bb93fe9d320d" : true
},
"following" : {
"87a8b6c8-7f72-45c2-a8c5-bb93fe9d320d" : true
},
"regUser" : "e3de536b-03a1-4fb4-b637-ebcebaae55c6",
"username" : "Sven8k"
}
}
}
The problem is: How can I display the actual content of the upload, when there is only a ID reference? I need a reference to the IDs for a user (userFeedRef) and a reference to the actual content of those specific IDs, not all uploads (uploadsRef).
How can I display this user ng-repeat in my html? So for example: ng-repeat {{feed.reasonUpload}} for user1 has to show:
Test
Test2
EDIT I've looked at this example, but I can't figure out how to render the content on the actual html feed in my case
var commentsRef =
new Firebase("https://awesome.firebaseio-demo.com/comments");
var linkRef =
new Firebase("https://awesome.firebaseio-demo.com/links");
var linkCommentsRef = linkRef.child(LINK_ID).child("comments");
linkCommentsRef.on("child_added", function(snap) {
commentsRef.child(snap.key()).once("value", function() {
// Render the comment on the link page.
));
});

You can do something like this:
$scope.finalData = (Object).values($scope.firebaseData.uploads);
//$scope.firebaseData is data what you retrieving from firebase.
Hope this plunker will help you.

Related

How to extract data from Firebase realtime database JSON-export

I have a Firebase realtime-database export-json that has nested informations, that I would like to extract. The structure of the JSON looks like this:
{
"users" : {
"024w97mv8NftGFY8THfQIU6PhaJ3" : {
"email" : "xxx",
"id" : "024w97mv8NftGFY8THfQIU6PhaJ3",
"name" : "xxx",
"items" : {
"-LQL9n-r9BGdo3HJZ2sk" : {
"disliked" : true,
"id" : 396,
"name" : "Aaa"
},
"-LQL9oO63nH-QW2w6zz0" : {
"liked" : true,
"id" : 3674,
"name" : "Bbb"
}
}
},
"0ERLT5DLRvbZUnjlnM7Ow0qItpz2" : {
"email" : "zzz",
"id" : "0ERLT5DLRvbZUnjlnM7Ow0qItpz2",
"name" : "zzz",
"items" : {
"-LIZnriSVQMzqTsPFNYa" : {
"id" : 396,
"liked" : true,
"name" : "Aaa"
},
"-LIZnrzOuk4WyjqEiLG8" : {
"disliked" : true,
"id" : 4805,
"name" : "Ccc"
}
}
}
}
}
What I need to achieve is getting a list of all liked item-names, and ideally counting how often an item is liked.
Is there a simple tool or script to do that? Ruby or Javascript would be preferred. Thanks a lot!
You can parse your JSON data in ruby like below
result_hash = JSON.parse(result)
result_ary = result_hash["users"].collect do |k,v|
v["items"].values.select{|v1| v1["liked"] == true }
end
result_data = result_ary.flatten
result of parsing
=> [{"liked"=>true, "id"=>3674, "name"=>"Bbb"}, {"id"=>396, "liked"=>true, "name"=>"Aaa"}]
Now its very easy for getting your required result
result_data.collect{|x| x["name"] }
=> ["Bbb", "Aaa"]
result_data.count {|x| x["name"] == "Aaa"}
=> 1
result_data.count {|x| x["name"] == "Bbb"}
=> 1

Firebase query taking forever

My firebase data looks like this...
In JSON down below...
I've been trying to use what I've found in their docs to query the db so that I end up with of all the terms and their keys. How do I query just the term property and key for every node under vocab? I'm using this to populate an autosuggest. Also, the 0 and 1 under the vocab node are keys... they showed up that way when I imported the data as a JSON file. Any new vocab goes in with unique long key values though.
I've tried both .on() and .equalTo()... But I have had no luck whatsoever. It always seems to be grabbing everything in the entire vocab node of the database and taking on the order of 7 whole seconds to do it each time. Here is an example of one of my attempts where I try to put just the terms into an array...
let termList = [];
const termsRef = firebase.database().ref('vocab/');
termsRef.on('child_added', snap => termList.push(snap.val().term));
This doesn't even get the keys (which I need) and it still takes around 7 seconds to do it. I've seen videos where people do things like this in one line and it goes quick... not my luck. Any help would be much appreciated.
As requested here is a JSON sample of one of the database nodes... there are over 400 like this... the relevant property is term... all the way at the bottom. I need an array of terms and firebase database keys. How do I get them with a query?
{
"date" : "2016-07-26T14:50:10.906Z",
"defs" : [ {
"AddedBy" : "",
"date" : "2016-07-26T14:50:10.906Z",
"def" : "it's your need to fulfill or to obtain your full potential, and have meaningful goals.",
"image" : ""
}, {
"AddedBy" : "",
"date" : "2016-07-26T14:50:10.906Z",
"def" : "the very last stage in priority in order to be happy.",
"image" : ""
}, {
"AddedBy" : "",
"date" : "2016-07-26T14:50:10.906Z",
"def" : "the need to be able to set goals and reach them and be able to accept one's self.",
"image" : ""
} ],
"examples" : [ {
"AddedBy" : "",
"addDate" : "2016-07-26T14:50:10.906Z",
"approved" : true,
"checkDate" : "2016-07-26T14:50:10.906Z",
"example" : "a self-actualizing person is a person who accepts themselves, sets realistic and meaningful goals and accepts change.",
"feedback" : {
"comment" : "",
"grammarTrouble" : false,
"incorrect" : false,
"moreSpecific" : false,
"noContext" : false
},
"nonExample" : false,
"seenRecently" : [ {
"sawOn" : "",
"user" : ""
} ]
}, {
"AddedBy" : "",
"addDate" : "2016-07-26T14:50:10.906Z",
"approved" : true,
"checkDate" : "2016-07-26T14:50:10.906Z",
"example" : "who is not self-actualizing is a person who dislikes themselves, has no goals in life, and refuses to accept change.",
"feedback" : {
"comment" : "",
"grammarTrouble" : false,
"incorrect" : false,
"moreSpecific" : false,
"noContext" : false
},
"nonExample" : false,
"seenRecently" : [ {
"sawOn" : "",
"user" : ""
} ]
}, {
"AddedBy" : "",
"addDate" : "2016-07-26T14:50:10.906Z",
"approved" : true,
"checkDate" : "2016-07-26T14:50:10.906Z",
"example" : "Someone who achieves to their best personal ability and faces every situation head on.",
"feedback" : {
"comment" : "",
"grammarTrouble" : false,
"incorrect" : false,
"moreSpecific" : false,
"noContext" : false
},
"nonExample" : false,
"seenRecently" : [ {
"sawOn" : "",
"user" : ""
} ]
} ],
"term" : "Self Actualization",
"unit" : 0
},

Combining orderByChild and equalTo in Firebase queries

Given the following data structure:
{
"comments" : {
"-JcBbk64Gpm1SKoFHv8b" : {
"content" : "blah",
"createdAt" : 1417550954985,
"link" : "http%3A%2F%2Flocalhost%3A3000%2F",
"recommendedCount" : 0,
"replies" : {
"-JcBbk8gF_nQ_vjwag61" : true
},
"replyCount" : 1
},
"-JcBbk8gF_nQ_vjwag61" : {
"content" : "blah blah",
"createdAt" : 1417550955151,
"link" : "http%3A%2F%2Flocalhost%3A3000%2F",
"recommendedCount" : 0,
"replyCount" : 1,
"replyToComment" : "-JcBbk64Gpm1SKoFHv8b"
}
},
"links" : {
"http%3A%2F%2Flocalhost%3A3000%2F" : {
"author" : 5,
"commentCount" : 2,
"comments" : {
"-JcBbk64Gpm1SKoFHv8b" : true,
"-JcBbk8gF_nQ_vjwag61" : true
},
"createdAt" : 1417550954931,
"ratingCount" : 2,
"recommendedCount" : 32,
"score" : 91,
"title" : "A Christian vs. an Atheist: Round 2",
"url" : "http://localhost:3000/"
}
}
}
I would like to retrieve all the comments for a given link and sort them in reverse chronological order. I've gotten this far, but I can't figure out how to do the reverse sort because I've already used orderByChild to narrow down the results by link:
ref.orderByChild('link').equalTo(currentLink).on('value', function (snap) {
console.log(snapshot.val());
});
If I call orderByChild() a second time like this:
ref.orderByChild('link').equalTo(currentLink).orderByChild('createdAt').on('value', function (snap) {
console.log(snapshot.val());
});
it fails with this error message:
Uncaught Error: Query.orderByChild: You can't combine multiple orderBy calls.
I'm stumped. Any suggestions?
I encountered the same issues on my firebase project and I solved that like this.
Please take a look.
var formRef = firebase.child('links').child(currentLink);
formRef.orderByChild('createdAt').on('value', function (snap) {
console.log(snapshot.val());
});
It will works.
Best Regards.

Unable to print BSON object from javascript

My mongoDB collection looks like this :
{
"_id" : ObjectId("5070310e0f3350482b00011d"),
"emails" : [
{
"_id" : ObjectId("5070310e0f3350482b000120"),
"_type" : "Email",
"name" : "work",
"email" : "peter.loescher#siemens.com",
"current" : true
}
]
}
and this is the .js code i use to print the contents :
c = db.contacts.findOne( { "emails.email" : { $ne : null } }, { "emails" : 1 } )
print(c._id.toString() + " " + c.emails[0]);
when I try to run this javascript file, it is just displaying the id but not the email array.
output:
5070310e0f3350482b00011d [object bson_object]
but when I try c.emails[0].email is is giving proper result. i.e. peter.loescher#siemens.com
All I need is I want to display the whole emails embedded object.
i.e.
"emails" : [
{
"_id" : ObjectId("5070310e0f3350482b000120"),
"_type" : "Email",
"name" : "work",
"email" : "peter.loescher#siemens.com",
"current" : true
}
]
Where I am going wrong?. Any help would be appreciated.
You need printjson to output a nicely formatted JSON:
printjson(c.emails[0]);
Here it is the documentation.

How to delete deep array in mongodb?

I am trying to delete "virtualNumber" : "12345" in the following document:
{
"_id" : ObjectId("50a9db5bdc7a04df06000005"),
"billingInfo" : null,
"date" : "dsfdsfsdfsd",
"description" : "sdfsdff",
"pbx" : {
"_id" : ObjectId("50a9db5bdc7a04df06000006"),
"did" : {
"1234567890" : {
"inventoryId" : "509df7547e84b25e18000001",
"didcountry" : "india",
"didState" : "bangalore",
"routeType" : "CallForward",
"didNumber" : "1234567890",
"didVirtualNumbers" : [
{
"virtualNumber" : "12345"
},
{
"virtualNumber" : "56789"
}
],
"id" : ObjectId("50a9db9acdfb4f9217000002")
}
},
},
I am using node.js, so I constructed a query in JavaScript:
var query = {_id: ObjectId("50a9db5bdc7a04df06000005")};
var obj = {};
obj["pbx.did.1234567890.didVirtualNumbers.virtualNumber"]=12345;
//problem
collection.update(query,{$pull:obj});
You need to match the array element like:
{"$pull": {"pbx.did.7259591220.didVirtualNumbers": {"virtualNumber": "12345"}}}
So you should change your code to:
obj["pbx.did.7259591220.didVirtualNumbers"]={"virtualNumber": "12345"};
Please refer to http://www.mongodb.org/display/DOCS/Updating#Updating-%24pull
It mentions the pull field should be an array.

Categories