簡體   English   中英

我可以在更新 Firestore 文檔時動態更改鍵和值嗎?

[英]can I dynamically change the key and value when updating Firestore document?

所以我有這樣的可調用雲函數:

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)
    }


})

正如您在.update({updatedKey: updatedValue})看到的,我想從客戶端設置鍵和值。 所以我可以動態更新文檔。 我希望updatedKeyupdatedValue來自客戶端

但我上面的代碼似乎不起作用,因為我有這個警告:

在此處輸入圖片說明

updatedKey已聲明但從未使用過。 那么如何在更新 Firestore 文檔時動態更改鍵和值呢? 我可以嗎?

這里的問題與 Cloud Functions 或 Firestore 無關。 這是 JavaScript 語法。 如果要使用變量的值作為對象的鍵,則需要對對象使用方括號語法

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

請注意updatedKey周圍的方括號告訴 JavaScript 您希望將變量的值替換為鍵的名稱。

你可以像這樣實現同樣的事情:

const object = {}
object[updatedKey] = updatedValue

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

為了有一個動態密鑰,你需要做這樣的事情

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM