Combining orderByChild and equalTo in Firebase queries - javascript

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.

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

MongoDb - Do i need an index on a second field when using deleteOne

I have a simple collection events
{
"_id" : ObjectId("5e2a9bb9dcb646448f9409b3"),
"year" : 2020,
"employee_id" : "5e1afe5ab7bad92b20365476",
"event" : ["Holidays"],
"total" : 21,
"used" : 1
}
and i don't want to be able to delete the documents that have used field grater than 0.
I use this
db.collection('events').deleteOne({_id: ObjectId("5e2a9bb9dcb646448f9409b3"), used: 0});
Do i need to set an index on used field if i already use _id?
Thanks
Not necessary. MongoDB already uses _id (unique index created by MongoDB) to delete documents.
db.collection('events').find({_id: ObjectId("5e2a9bb9dcb646448f9409b3"), used: 0}).explain();
"winningPlan" : {
"stage" : "FETCH",
"filter" : {
"used" : {
"$eq" : 0.0
}
},
"inputStage" : {
"stage" : "IXSCAN",
"keyPattern" : {
"_id" : 1
},
"indexName" : "_id_",
"isMultiKey" : false,
"multiKeyPaths" : {
"_id" : []
},
"isUnique" : true,
"isSparse" : false,
"isPartial" : false,
"indexVersion" : 2,
"direction" : "forward",
"indexBounds" : {
"_id" : [
"[ObjectId('5e2a9bb9dcb646448f9409b3'), ObjectId('5e2a9bb9dcb646448f9409b3')]"
]
}
}
}

How to query Firebase based on boolean value?

"vehicles" : {
"-KbwlIGLm6dxffPJoJJB" : {
"fuel" : "petrol",
"groups" : {
"-KdWh_9KVF16efcSdrji" : true,
"-Kdb1G720MDgbuR3nPBL" : true
},
"make" : "Honda",
"model" : "City",
"name" : "Honda City",
"speed_limit" : 100,
"tank_size" : 32,
"type" : "car"
},
"-KdU-BlfEdqzKxFjGI3D" : {
"fuel" : "petrol",
"groups" : {
"-KdWh_9KVF16efcSdrji" : true
},
"make" : "yamaha",
"model" : "FZ",
"name" : "Yamaza FZ",
"speed_limit" : 60,
"tank_size" : 12,
"type" : "bike"
}
}
I want to retrieve results where groups has the -KdWh_9KVF16efcSdrji and the key must equal to true.
vehicles_ref.child("groups").orderByChild("-KdWh_9KVF16efcSdrji").equalTo(true).on
("value", function (snapshot) {
console.log(snapshot.val());
});
But currently I'm getting NULL for the above criteria.
i have changed query
vehicles_ref.orderByChild("/groups/-KdWh_9KVF16efcSdrji").equalTo(true).on("value", function (snapshot) {
console.log(snapshot.val());
});
now getting results, but now getting warning
FIREBASE WARNING: Using an unspecified index. Consider adding ".indexOn": "groups/-KdWh_9KVF16efcSdrji" at /vehicles to your security rules for better performance
how to add index to remove this warning ?
I also had that warning that I sent firebase, and I was filtering queries in the queries looking for items with the same id. The warning message ".indexOn" refers to the rule in your database, which should be checked by adding ".indexOn" to the group you are trying to sort the items in.
{
"scores": {
"bruhathkayosaurus" : 55,
"lambeosaurus" : 21,
"linhenykus" : 80,
"pterodactyl" : 93,
"stegosaurus" : 5,
"triceratops" : 22
}
}
Because the names of the dinosaurs are just the keys.
we can add a .value rule to our node / scores to optimize our queries:
{
"rules": {
"scores": {
".indexOn": ".value"
}
}
}
you can use the following link:
https://firebase.google.com/docs/database/security/indexing-data?hl=es-419

Display relational data in Firebase using AngularJS

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.

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