【问题标题】:Update Firestore Field, but field is a varaible [duplicate]更新 Firestore 字段,但字段是变量 [重复]
【发布时间】:2020-11-01 19:20:25
【问题描述】:

是否可以通过firestore作为变量传递要更新的字段?

我想创建一个函数来更新文档,例如...

updateFirebaseDocument('enquiries', 'asdaasdasds, 'status', '1'))

具有以下功能

export async function updateFirebaseDocument(collectionName, documentId, field, updateValue) {
    var doc = db.collection(collectionName).doc(documentId)
    return doc.update({
        field: updateValue
    })
    .then(function() {
        console.log("Document successfully updated!");
    })
    .catch(function(error) {
        // The document probably doesn't exist.
        console.error("Error updating document: ", error);
    });
}

这确实有效,但问题是,它创建了一个名为 field 的字段,而不是更新 status 字段。有没有办法做到这一点,而不是对更新字段进行硬编码?

【问题讨论】:

    标签: javascript firebase google-cloud-firestore


    【解决方案1】:

    你可以不用 ES6

    export async function updateFirebaseDocument(collectionName, documentId, field, updateValue) {
        var doc = db.collection(collectionName).doc(documentId)
    
        var obj = {}
        obj[field] = updateValue;
     
        return doc.update(obj)
        .then(function() {
            console.log("Document successfully updated!");
        })
        .catch(function(error) {
            // The document probably doesn't exist.
            console.error("Error updating document: ", error);
        });
    }
    

    【讨论】:

      【解决方案2】:

      使用方括号为我解决了这个问题。

            [field]: updateValue
      
      

      【讨论】:

      • 这个词是object's property or key,所以我们不会混淆:)。是的,您可以使用 ComputedPropertyName 作为您演示的对象文字语法的一部分。但这仅适用于 ES6。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-07-20
      • 1970-01-01
      • 1970-01-01
      • 2018-05-25
      • 1970-01-01
      • 2014-10-11
      • 2016-01-17
      相关资源
      最近更新 更多