0

so I have callable cloud function like this:

const db = admin.firestore()

exports.changeEventDataInUserSubcollection = functions.https.onCall(async (data, context) => {


    const updatedKey = data.updatedKey
    const updatedValue = data.updatedValue
    const creatorID = data.creatorID
    const eventID = data.eventID

    try {

        return db.doc(`users/${creatorID}/createdEvents/${eventID}`).update({updatedKey: updatedValue})


    } catch (error) {
        console.log(error)
        return Promise.resolve(null)
    }


})

as you can see in .update({updatedKey: updatedValue}), I want to set the key and value from the client side. so I can update the document dynamically. I want the updatedKey and updatedValue come from client side

but my code above seems will not work, because I have this warning:

enter image description here

updatedKey is declared but never used. so how to dynamically change the key and value when updating Firestore document ? can I do that ?

Alexa289
  • 8,089
  • 10
  • 74
  • 178

2 Answers2

4

The issue here doesn't have anything to do with Cloud Functions or Firestore. It's JavaScript syntax. If you want to use the value of a variable as the key of an object you, need to use square bracket syntax for the object:

return db
    .doc(`users/${creatorID}/createdEvents/${eventID}`)
    .update({ [updatedKey]: updatedValue })

Note the square brackets around updatedKey that tell JavaScript that you want to substitute the value of the variable as the name of the key.

You could have achieved the same thing like this:

const object = {}
object[updatedKey] = updatedValue

return db
    .doc(`users/${creatorID}/createdEvents/${eventID}`)
    .update(object)
Doug Stevenson
  • 297,357
  • 32
  • 422
  • 441
1

In order to have a dynamic key you need to do do something like this

 return db.doc(`users/${creatorID}/createdEvents/${eventID}`).update({[updatedKey]: updatedValue});
Abito Prakash
  • 4,368
  • 2
  • 13
  • 26