【问题标题】:can I dynamically change the key and value when updating Firestore document?更新 Firestore 文档时可以动态更改键和值吗?
【发布时间】:2019-12-17 07:53:00
【问题描述】:

所以我有这样的可调用云函数:

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 文档时动态更改键和值呢?我可以这样做吗?

【问题讨论】:

    标签: javascript firebase google-cloud-firestore google-cloud-functions


    【解决方案1】:

    这里的问题与 Cloud Functions 或 Firestore 无关。它是 JavaScript 语法。如果你想使用一个变量的值作为一个对象的键,你需要使用square bracket syntax作为对象:

    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)
    

    【讨论】:

      【解决方案2】:

      为了获得动态密钥,您需要执行以下操作

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-06-01
        • 1970-01-01
        • 2020-02-04
        • 2019-06-21
        • 1970-01-01
        • 2019-12-11
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多