简体   繁体   中英

Delete first node in Firebase through Cloud Functions

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"

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() .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM