Unable to delete entry in Firebase database using remove - firebase

I'm trying to remove an entry from my Firebase database, but am not able to delete it.
Here's my database structure:
Here's what I've tried:
let subRefs = firebase.database().ref('subscriptions/' + userId).once('value').then(function(snapshot){
let objs = snapshot.val();
for (let key in objs){
if (objs[key].uid == memberId){
console.log('found'); // I see this in the console
//remove the subscription
let ref = firebase.database().ref('subscription/' + userId + '/' + key);
ref.remove().then(function() {
console.log("Remove succeeded");
}).catch(function(error) {
console.log("Remove failed");
});
}
}
});
I've also tried the following approach as suggested here in the docs, but that didn't work either.
let update = {};
update['subscription/' + userId + '/' + key] = null;
firebase.database().ref().update(update).then(function(){
console.log('remove success');
}).catch(function(err){
console.log('remove failed');
});
In both cases, I see the "remove success" log, but when I check the database, it's not actually deleted.

Related

Firebase Cloud Functions wait for variables

I wanna write img_thumb_url to firebase database. In func1A, my code i wrote below where I expect it can breakthrough the while loop when those global variable room and msg_key are not null but what I found it always undefined although those variables become defined with string value when func2B successfully trigggered.
...
while(1){
if(room!=null && msg_key!=null){
console.log('room is ', room, '. msg_key is ', msg_key);
console.log('break from the loop');
break;
}
}
admin.initializeApp();
return admin.database().ref('/msgs/' + room + '/chat/' + msg_key + '/attachment/photo/thumbnail/url2').set(img_thumb_url);
})
But the path above ' '/msgs/' + room + '/chat/' + msg_key + '/attachment/photo/thumbnail/url2 ' depends on variable room and msg_key retrieved from other function func2B which is here,
exports.func2B = functions.database.ref('/msgs/{roomName}/chat/{pushid}')
.onCreate((snapshot, context) => {
// Grab the current value of what was written to the Realtime Database.
const msg = snapshot.val();
if (msg.attachPhotoUrl == null) {
console.log('No photo attachment found');
return null;
}
if (msg_key != null) {
console.log('msg_key no longer null');
return null;
}
console.log('writing url2 for thumbnail in firebase database...');
msg_key = msg.key;
room = msg.roomName;
console.log('room is ',room);
console.log('msg_key is ',msg_key);
console.log('img_thumb_url: ',img_thumb_url);
return ....
});
I'm not sure whether this is the proper way of method but I don't think it is as simple as that. Please help me how to resolve. How can i get that assigned value variable room and msg_key in func2B to func1A?

Checking a child's entries for a match

let ref = firebase.database().ref('players').child(playerId).child('voters');
ref.child(uid).once('value', snap => {
var key = snap.key;
console.log("snapkey: " + key + " uid: " + uid)
if (key === uid) {
console.log("Exists")
} else {
console.log("Doesn't exist")
}
});
I'm trying to see if a variable uid, which holds the users unique ID from firebase-auth is present in my database's voters
So for me, when I'm using the app, my uid is vKl6rIUuI0WsbeWVORz3twPUfnd2. So if I go to vote on this Firstname Lastname person, it should tell me I exist in the above image's scenario.
The problem is, it seems to always say it exists. The console.log for key and uid are both putting out my uid. Is it something with the ref.child(uid)...?
let ref = firebase.database().ref('/players/' + playerID + '/voters');
ref.once('value', snap => {
var value = snap.val()
console.log(value)
if (value !== null) {
console.log("Exists")
} else {
console.log("Doesn't exist")
}
});
https://firebase.google.com/docs/database/web/read-and-write#read_data_once
A snapshot will always have a key. Always. And it will be at the location you requested by reference. Whether or not there is data behind that key is irrelevant to the fact that the snapshot will always have a key.
What you need to do is check the data behind that key. Is it null? Then there's no data there. A number? That's data, and it's present.
Use .exists() method:
let ref = firebase.database().ref('players').child(playerId).child('voters');
ref.child(uid).once('value', (snap) => {
console.log(snap.exists()); // This will print true or false
});

How to get a data from firestore while using batch?

I want to perform a batch transaction in firestore. I am storing last key in other collection.
i need to get the last key then increase by 1, then create two documents using this key. How can i do this?
let lastDealKeyRef = this.db.collection('counters').doc('dealCounter')
let dealsRef = this.db.collection('deals').doc(id)
let lastDealKey = batch.get(lastDealKeyRef) // here is the problem..
batch.set(dealsRef, dealData)
let contentRef = this.db.collection('contents').doc('deal' + id)
batch.set(contentRef, {'html': '<p>Hello World</p>' + lastDealKey })
batch.commit().then(function () {
console.log('done') })
If you want to read/write data in a single operation you should be using a transaction.
// Set up all references
let lastDealKeyRef = this.db.collection('counters').doc('dealCounter');
let dealsRef = this.db.collection('deals').doc(id);
let contentRef = this.db.collection('contents').doc('deal' + id);
// Begin a transaction
db.runTransaction(function(transaction) {
// Get the data you want to read
return transaction.get(lastDealKeyRef).then(function(lastDealDoc) {
let lastDealData = lastDealDoc.data();
// Set all data
let setDeals = transaction.set(dealsRef, dealData);
let setContent = transaction.set(contentRef, {'html': '<p>Hello World</p>' + lastDealKey });
// Return a promise
return Promise.all([setDeals, setContent]);
});
}).then(function() {
console.log("Transaction success.");
}).catch(function(err) {
console.error("Transaction failure: " + err);
});
You can read more about transactions and batches here:
https://firebase.google.com/docs/firestore/manage-data/transactions

Querying another easy table for push notification message

I have two easy tables configured in my Azure App backend:
Services with Id and ServiceName properties
ServiceDetails with Id, ServiceID and ServiceDetailDate properties
Whenever a new ServiceDetails entry is inserted, I want to send a message to my users via Push Notifications containing information about ServiceDetailDate and ServiceName.
So my question is how can I query another table to obtain information from it? In this case the ServiceID (from ServiceDetails table) is known, so I want to get the ServiceName from Services. Which code should I add to extract the ServiceName from the serviceInfo object (in the payload message) to my script to fulfill this request?
Actually I'm not sure about the query and serviceInfo instructions, so if I'm wrong with the code, don't hesitate to point me in the right direction.
var azureMobileApps = require('azure-mobile-apps'),
promises = require('azure-mobile-apps/src/utilities/promises'),
logger = require('azure-mobile-apps/src/logger'),
queries = require('azure-mobile-apps/src/query');
var table = azureMobileApps.table();
table.insert(function (context) {
var query = queries.create('Services');
var serviceInfo = query.where({'Id': context.item.ServiceID});
var payload = '{"messageParam": "Your service -service name- has been added on ' + context.item.ServiceDetailDate + '" }';
return context.execute()
.then(function (results) {
if (context.push) {
context.push.send(null, payload, function (error) {
if (error) {
logger.error('Error while sending push notification: ', error);
} else {
logger.info('Push notification sent successfully!');
}
});
}
return results;
})
.catch(function (error) {
logger.error('Error while running context.execute: ', error);
});
});
module.exports = table;
Thanks for your help.
You can use the following code to query another easy table in ServiceDetails.js.
table.insert(function (context) {
return context.tables('Services')
.where({ Id: context.item.ServiceID })
.select('ServiceName')
.read()
.then(function (data) {
var message = 'Your service ' + data[0].ServiceName + ' has been added on ' + context.item.ServiceDetailDate;
var payload = '{"messageParam": "' + message + '"}';
return context.execute().then(function (results) {
//..
});
});
});

$firebaseArray $indexFor() not finding key when given value

I have this firebase:
users: {
userId: {
notifications: {
notificationId: "Notification"
}
}
}
When given "Notification", I'm trying to find its notificationId (which is generated from the push() method) so I can eventually delete it. According to the docs, the $indexFor() method should do this for me. Here's my code:
var ref = new Firebase('https://url.firebaseio.com/');
$scope.dismissNotification = function(notification) {
var notificationRef = ref.child('users/' + $scope.currentUser.id + '/notifications');
var notifications = $firebaseArray(notificationRef);
notifications.$loaded().then(function(data) {
console.log(data);
console.log(data.$indexFor(notification));
}).catch(function(error) {
console.log('Error: ' + error);
});
};
The first log is the correct object with the notification string inside that I'm looking for, but the second log returns -1, when I want it to return the notificationId associated with it.
Not sure what you're trying to accomplish, but this is the simplest way to find the key for a given value:
var notificationRef = ref.child('users/' + $scope.currentUser.id + '/notifications');
var query = notificationRef.orderByValue().equalTo(notification);
query.once('child_added', function(snapshot) {
console.log(snapshot.key());
});

Resources