Reputation: 3234
I have a list of users, which contains a node called scannedCards
, which contains an array of cardIds
. Below is a screenshot of one user.
There are multiple users like above, I want to delete all the card Ids if they are equalTo(Some Card Id)
, I want to this with all the users at once.
Below is the query I a using:
const ref = database.ref('users');
const query = ref.orderByChild('cardId').equalTo(cardId);
But the result is always empty, Can someone please tell how I can achieve this?
Upvotes: 1
Views: 878
Reputation: 5918
The query you listed above doesn't seem to be returning anything because, based on the screenshot provided, cardId
isn't a direct child property of users, but rather a property of each object under the scannedCards
list that users may have.
If you only need to do this as part of a one-time operation, you may run something like this:
const ref = database.ref('users');
ref.once('value').then(snapshot => {
const users = snapshot.val();
for (var user_id in users) {
const scannedCards = users[user_id].scannedCards;
for (var card in scannedCards) {
if (scannedCards[card].card_id == "<some card id>") {
firebase.database().ref(`users/${user_id}/scannedCards/${card_id}`)
.set(null);
}
}
}
});
If you plan on letting logged-in users delete their scanned cards, it would be a little bit less complicated:
// user_id is for whoever is logged in
const ref = firebase.database().ref(`users/${user_id}/scannedCards`);
ref.once('value').then(snapshot => {
const scannedCards = snapshot.val();
for (var card in scannedCards) {
if (scannedCards[card].card_id == "<some card id>") {
firebase.database().ref(`users/${user_id}/scannedCards/${card_id}`)
.set(null)
}
}
});
Also worth pointing out, scannedCards
is not an array of card ids, because the keys are object ids and the values are objects (which contain cardId and userId properties).
Upvotes: 5