简体   繁体   中英

How to delete one entry from an map of a Firestore document using Cloud Functions

This question is specifically about how to delete a field from a map in a Firestore document through cloud function in 2023. The Firebase team released tons of SDKs, each of which has several versions with breaking changes. So although it might seem like a duplicate to the untrained eye, it is not.

How can I delete one field from a map in a Firestore document using cloud functions?

My document "/groups/{groupId}" looks like this:

{
  members: {
    userIdOfUserA: {
      <some fields that contain info about user A>
    },
    userIdOfUserB: {
      <some fields that contain info about user B>
    }
  }
}

The function looks like this:

const functions = require("firebase-functions")

exports.deleteUserProfileFromGroup = functions.firestore
  .document("/groups/{groupId}/members/{userid}")
  .onDelete((snapshot, context) => {
    const admin = require("firebase-admin")
    admin.initializeApp()

    const docRef = admin.firestore().doc("groups/" + context.params.groupId)
    return docRef.update({
      members: admin.firestore
        .FieldValue
        .delete(context.params.userId)
    })
  })

If the document "groups/{groupId}/members/userIdOfUserA" is being deleted, the function is correctly being triggered, but instead of only deleting the key "userIdOfUserA" with its data from the map, it deletes the whole "members" map.

So I suppose that is the wrong function to do this or the wrong way I'm feeding the key into the function but I could not find any information how to do it right.

Thank you for being my rubber duck. I remembered that map values can be accessed directly: This is how you can delete a field from a map by its key:

const functions = require("firebase-functions")

exports.deleteUserProfileFromGroup = functions.firestore
  .document("/groups/{groupId}/members/{userid}")
  .onDelete((snapshot, context) => {
    const admin = require("firebase-admin")
    admin.initializeApp()

    const docRef = admin.firestore().doc("groups/" + context.params.groupId)
    return docRef.update({
      [`members.${context.params.userId}`]: admin.firestore
        .FieldValue
        .delete()
    })
  })

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