Reputation: 245
This is my code in cloud functions:
exports.PlayedMinigameSlot = functions.database.ref('/play/slot/{uid}/').onWrite(event => {
if (!event.data.exists()) {
return
}
const val = event.data.val()
return db.ref(`/users/${event.params.uid}/server/slot/games/`).limitToFirst(1).once('value').then(function(slotValue) {
const key = slotValue.key
const wonIndex = slotValue.val()
console.log(wonIndex)
console.log(key)
return db.ref(`/users/${event.params.uid}/server/slot/games/${key}`).remove().then(snap => {
return event.data.adminRef.remove()
})
})
})
My console return first: null (for wonIndex) and than "games" for "key".
This is my database:
How can I delete first first row under "games", so in this case "1:1"
Upvotes: 0
Views: 514
Reputation: 598797
When you call limitToFirst()
you create a query. And when you execute a query against the Firebase Database, there will potentially be multiple results. So the snapshot contains a list of those results. Even if there is only a single result, the snapshot will contain a list of one result.
Your code needs to handle this list, which it currently doesn't.
return db.ref(`/users/${event.params.uid}/server/slot/games/`).limitToFirst(1).once('value').then(function(slotValues) {
if (slotValue.exists()) {
var location;
slotValues.forEach(function(slotValue) {
const key = slotValue.key
const wonIndex = slotValue.val()
location = `/users/${event.params.uid}/server/slot/games/${key}`;
});
return db.ref(location).remove().then(snap => {
return event.data.adminRef.remove()
});
});
})
This purely works for a single location. If you have more locations, either use a single multi-location update (with null
values to signal what locations to remove) or use multiple promises with Promise.all()
.
Upvotes: 1