Firebase query delete specific uid Real Time Database (Javascript) - javascript

I have this data on my firebase:
transportation: {
"car" : {
"bus" : {
"toyota" : true,
"bmw" : true
},
"suv" : {
"honda" : true,
"toyota" : true,
}
}
}
I want to delete all "toyota" data so that my data looks like this:
transportation: {
"car" : {
"bus" : {
"bmw" : true
},
"suv" : {
"honda" : true,
}
}
}

The best possible way to do is check the value using loop in Javascript manually and delete if it's "toyota".
var firebaseRef= firebase.database().ref('transportation/');
firebaseRef.on("value", function(data)){
var datKey=data.key;
firebase.database().ref('transportation/'+datKey).on("value",function(childData)){
var childDataKey=childData.key;
firebase.database().ref('transportation/'+datKey+'/'+childDataKey+'/').on("value",function(data)){
firebase.database().ref('transportation/'+dataKey+'/'+childDataKey+'toyota').remove();
}
}
}

Related

How to retrieve data from realtime database using indexOn in cloud functions

Firebase structure:
{
"config" : [
{
"config1" : {
"hideimage" : true
}
},
{
"config2" : {
"hideimage" : false
}
}
]
}
Database rules:
"config": {
".indexOn": ["hideimage"]
}
I'm trying to retrieve all config items that have hideimage attribute set to true using:
admin.database().ref('config').orderByChild("hideimage").equalTo(true).once('value', result => {});
The expected result should be:
[{
"config1" : {
"hideimage" : true
}
}]
but I'm retrieving a null response without getting any error.
Your data structure contains two nested levels:
you have an array
inside the first array element, you have config1 and config2
You can see this if you look at the Firebase console, where your data will show like:
{
"config" : {
"0": {
"config1" : {
"hideimage" : true
}
},
{
"config2" : {
"hideimage" : false
}
}
}
}
Firebase can only query nodes in a flat list, not a tree. So with your current data structure it can only find the node with hideimage=true under /config/0, not under all /config children.
Since you're already naming your config1 and config2 uniquely, I think the array may be a mistake, and you're really looking for:
{
"config": {
"config1" : {
"hideimage" : true
},
"config2" : {
"hideimage" : false
}
}
}
With this data structure your query will work.

Mongoose - go through object

Using mongoose on node.js I'm trying to find all games where player game.players.id equals the id I passed.
Schema:
var Game = mongoose.Schema({
id: String,
date: { type: Date, default: Date.now },
game: Object,
isOnline: Boolean
});
I'm not sure what is wrong in this function but it returns empty array:
var specificGameStatistics = function (user, game) {
var deferred = q.defer()
Game.find({ "game.players.id" : user, "game.rules.gameType": game.gameType, "game.rules.quatro": game.quatro}, function(err, data) {
deferred.resolve(data);
});
return deferred.promise;
}
////////////////////USAGE///////////////
var testGame = {rules: {gameType : 1, quatro : null}}
UsersCtrl.specificGameStatistics(data.id, testGame).then(function(userData) {
console.log(userData);
});
And here is the example of the game already saved in database:
{
"isOnline" : true,
"game" : {
"numberOfPlayers" : NumberInt("1"),
"players" : [
{
"id" : "58a2c0ecd8ba9f8602836870",
"name" : "PlayerName",
"type" : NumberInt("1"),
"avgStatistic" : "30.00",
"numbersHit" : NumberInt("1"),
"totalScore" : NumberInt("60"),
..............................
}
], //there is more players here
"rules" : {
"gameType" : NumberInt("1"),
"quatro" : null,
"rounds" : NumberInt("1"),
} // there is more in JSON object
...............................
"_id" : ObjectId("58aed4aeea20ecdf0c426838"),
"date" : ISODate("2017-02-23T13:25:18.284+01:00"),
"__v" : NumberInt("0")
}
I have tested the player ID to be equal and it is but still it returns empty array. Test code:
///////////TEST//////////////
console.log(data.id, "58a2c0ecd8ba9f8602836870");
if (data.id === "58a2c0ecd8ba9f8602836870") {console.log("this is true");}
var testGame = {rules: {gameType : 1, quatro : null}}
UsersCtrl.specificGameStatistics(data.id, testGame).then(function(userData) {
console.log(userData);
});
//////////TEST///////////////
and it returns:
58a2c0ecd8ba9f8602836870 58a2c0ecd8ba9f8602836870
this is true
[]
--------------------------------------------------------------------------------------------------------
Answer: With help of Deividas Karžinauskas the solution is:
Game.where('game.players.id', user).where('game.rules.gameType', game.rules.gameType).find({}, function(err, data) { //, "game.rules.quatro": game.quatro
deferred.resolve(data);
});
This is because of the additional rules that you specify ({gameType : 1, quatro : null}), which do not exist in the player object (
{
"id" : "58a2c0ecd8ba9f8602836870",
"name" : "PlayerName",
"type" : NumberInt("1"),
"avgStatistic" : "30.00",
"numbersHit" : NumberInt("1"),
"totalScore" : NumberInt("60"),
..............................
}
). You can confirm this by simply looking for a game by id.
If you want to add these rules then you should find all games which match these rules and then look for the games of a specific player.

How select data with given condition

I have following data.
{
"name" : "Maria",
"facebook" : [
{
"data" : "fb.com",
"privacy" : true
}
],
"twitter" : [
{
"data" : "twitter.com",
"privacy" : false
}
],
"google" : [
{
"data" : "google.com",
"privacy" : true
}
],
"phno" : [
{
"data" : "+1-1289741824124",
"privacy" : true
}
]
}
I want to return only data having privacy is equal to true. How do I do it ?
I tried but it returns all data having privacy is equal to false also. How do I query the data ?
Please post MongoDB query not Javascript code.
Thanks!
edit
having structure like this:
{
"_id" : ObjectId("575e4c8731dcfb59af388e1d"),
"name" : "Maria",
"providers" : [
{
"type" : "facebook",
"data" : "fb.com",
"privacy" : true
},
{
"type" : "twitter",
"data" : "twitter.com",
"privacy" : false
},
{
"type" : "google",
"data" : "google.com",
"privacy" : true
},
{
"type" : "phno",
"data" : "+1-1289741824124",
"privacy" : true
}
]
}
with query like this:
db.maria.aggregate([{
$project : {
_id : 1,
name : 1,
"providers" : {
$filter : {
input : "$providers",
as : "p",
cond : {
$eq : ["$$p.privacy", true]
}
}
}
}
}
])
])
we are gaining dynamic output, and we don't need to take care about provider name as this is covered by generic structure
{
"providers" : [
{
"type" : "facebook",
"data" : "fb.com",
"privacy" : true
},
{
"type" : "google",
"data" : "google.com",
"privacy" : true
},
{
"type" : "phno",
"data" : "+1-1289741824124",
"privacy" : true
}
],
"name" : "Maria"
}
end of edit
The way you could get this is using aggregation framework.
As we have an array for each field, we need to unwind it first, then we can use $project to set field value or simply null. As this looks like a simple query, it could give a bit of trouble. The way we can improve that is change a document structure, to have an array of providers and simple providerType field.
Aggregation stages below:
db.maria.find()
var unwindFb = {
$unwind : "$facebook"
}
var unwindtw = {
$unwind : "$twitter"
}
var unwindgo = {
$unwind : "$google"
}
var unwindph = {
$unwind : "$phno"
}
var project = {
$project : {
_id : 1,
name : 1, // list other fields here
facebook : {
$cond : {
if : {
$gte : ["$facebook.privacy", true]
},
then : [{
data : "$facebook.data",
privacy : "$facebook.privacy"
}
],
else : null
}
},
twitter : {
$cond : {
if : {
$gte : ["$twitter.privacy", true]
},
then : [{
data : "$twitter.data",
privacy : "$twitter.privacy"
}
],
else : null
}
},
google : {
$cond : {
if : {
$gte : ["$google.privacy", true]
},
then : [{
data : "$google.data",
privacy : "$google.privacy"
}
],
else : null
}
},
phno : {
$cond : {
if : {
$gte : ["$phno.privacy", true]
},
then : [{
data : "$phno.data",
privacy : "$phno.privacy"
}
],
else : null
}
}
}
}
db.maria.aggregate([unwindFb, unwindtw, unwindgo, unwindph, project])
then output looks like this:
{
"_id" : ObjectId("575df49d31dcfb59af388e1a"),
"name" : "Maria",
"facebook" : [
{
"data" : "fb.com",
"privacy" : true
}
],
"twitter" : null,
"google" : [
{
"data" : "google.com",
"privacy" : true
}
],
"phno" : [
{
"data" : "+1-1289741824124",
"privacy" : true
}
]
}
you can use the below code to iterate the object and check for the privacy true
var list = {
"name" : "Maria",
"facebook" : [
{
"data" : "fb.com",
"privacy" : true
}
],
"twitter" : [
{
"data" : "twitter.com",
"privacy" : false
}
],
"google" : [
{
"data" : "google.com",
"privacy" : true
}
],
"phno" : [
{
"data" : "+1-1289741824124",
"privacy" : true
}
]
}
$.each(Object.keys(list), function(index,value){
if(list[value][0].privacy)
{
console.log(list[value][0]);
}
});
If you are open to use lodash ...this is how you can do it...
var tmp = {
...you json here
}
var res =[];//result array of filtered data
_.forIn(tmp, function (o) {
if (Array.isArray(o)) {
if (o[0].privacy === true) {
res.push(o);
}
}
});

How to get element from collection in Meteor if it multi-dimensional array or object or both?

I have collection "groups". like this:
{
"_id" : "e9sc7ogDp8pwY2uSX",
"groupName" : "one",
"creator" : "KPi9JwvEohKJsFyL4",
"eventDate" : "",
"isEvent" : true,
"eventStatus" : "Event announced",
"user" : [
{
"id" : "xfaAjgcSpSeGdmBuv",
"username" : "1#gmail.com",
"email" : "1#gmail.com",
"order" : [ ],
"price" : [ ],
"confirm" : false,
"complete" : false,
"emailText" : ""
},
...
],
...
"buyingStatus" : false,
"emailTextConfirmOrder" : " With love, your Pizzaday!! "
}
How can I get a value of specific element? For example i need to get value of "Groups.user.confirm" of specific group and specific user.
I tried to do so in methods.js
'pizzaDay.user.confirm': function(thisGroupeId, thisUser){
return Groups.find({ _id: thisGroupeId },{"user": ""},{"id": thisUser}).confirm
},
but it returns nothing.
Even in mongo console I can get just users array using
db.groups.findOne({ _id: "e9sc7ogDp8pwY2uSX"},{"user": ""})
The whole code is github
http://github.com/sysstas/pizzaday2
Try the following query:-
db.groups.aggregate(
[
{
$match:
{
_id: thisGroupeId,
"user.id": thisUser
}
},
{
$project:
{
groupName : 1,
//Add other fields of `user` level, if want to project those as well.
user:
{
"$setDifference":
[{
"$map":
{
"input": "$user",
"as": "o",
"in":
{
$eq : ["$$o.id" , thisUser] //Updated here
}
}
},[false]
]
}
}
}
]);
The above query will give the object(s) matching the query in $match inside user array. Now you can access any field you want of that particular object.
'pizzaDay.user.confirm': function(){
return Groups.findOne({ _id: thisGroupeId }).user.confirm;
I resolved it using this:
Template.Pizzaday.helpers({
confirm: function(){
let isConfirm = Groups.findOne(
{_id: Session.get("idgroupe")}).user.filter(
function(v){
return v.id === Meteor.userId();
})[0].confirm;
return isConfirm;
},
});
But I still think that there is some much elegant way to do that.

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.

Categories