0

Is it possible to pass the field to be updated withing firestore as a variable?

I want to create an a function to update a document such as...

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

with the following function

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

Which does work, but the issue is, that it creates a field called field, rather then updating the status field. Is there a way of doing this rather then hard-coding the update fields?

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
user5067291
  • 440
  • 1
  • 6
  • 16

2 Answers2

1

You can do without 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);
    });
}
Vinay
  • 7,442
  • 6
  • 25
  • 48
0

Using square brackets solved this for me.

      [field]: updateValue

user5067291
  • 440
  • 1
  • 6
  • 16
  • The term is the `object's property or key`, so we are not confused :). Yes, you can use `ComputedPropertyName` as part of the grammar for object literals as you demonstrated. But that only works for ES6. – Luka Jul 12 '20 at 13:28