spoky
spoky

Reputation: 27

Firestore: Dynamically Update Document (web)

Taken from the official guide document from the Google Firebase website, let's say I want to update a document.

var washingtonRef = db.collection("cities").doc("DC");

// Set the "capital" field of the city 'DC'
return washingtonRef.update({
    capital: true
})
.then(function() {
    console.log("Document successfully updated!");
})
.catch(function(error) {
    // The document probably doesn't exist.
    console.error("Error updating document: ", error);
});

As you notice, I could put a variable in the collection brackets, in the document brackets, and in the value, I want to assign to my field. However, I cannot use a variable for the field name. If I write something like this

var collection = "people";
var document = "john";
var value = 5;
var field = "result";

var docRef= db.collection(collection).doc(document);

return docRef.update({
    field: value
})
.then(function() {
    console.log("Document successfully updated!");
})
.catch(function(error) {
    // The document probably doesn't exist.
    console.error("Error updating document: ", error);
});

, it would all work except for the field variable. In the firestore database, it would update the field named "field" (or more like create a new one) in the "john" document in the "people" collection with number 5. What I was trying to achieve was to have a "john" document in the "people" collection with a field named "result" with a value of the number 5.

I want to have one function that takes all 4 variables and updates a certain field in a certain document in a certain collection. Is this possible? Does anybody know a way around this?

Thank you all for your answers.

Upvotes: 0

Views: 249

Answers (1)

Renaud Tarnec
Renaud Tarnec

Reputation: 83181

You should use the square brackets notation, as follows:

var collection = "people";
var document = "john";
var value = 5;
var fieldName = "result";

var obj = {};
obj[fieldName] = value;

var docRef= db.collection(collection).doc(document);

return docRef.update(obj)
.then(function() {
    console.log("Document successfully updated!");
})
.catch(function(error) {
    // The document probably doesn't exist.
    console.error("Error updating document: ", error);
});

Upvotes: 2

Related Questions