Reputation: 1245
I want to update a map in Firestore using cloud Function typed in Typescript, so I made this code but it doesn't work:
import * as functions from 'firebase-functions';
import * as admin from 'firebase-admin';
admin.initializeApp(functions.config().firebase);
exports.sendNote = functions.https.onCall(async(data,context)=>{
const numeroSender: string = data['numeroSender'];
const amisA = admin.firestore().collection('Amis').doc(numeroReceiver);
const connaissanceABBA:number = 3.0;
const version:number = 1;
await amisA.update({
'amis.${numeroSender}' : [connaissanceABBA,version]
});
});
the editor doesn't replace numeroSender by its value, and I tried also with:
'amis.'+numeroSender
and the editor is asking a semicolon and show many other errors. Even I tried to try this way:
const mapA: string = ("amis."+numeroSender);
console.log(mapA);
await amisA.update({
mapA : [connaissanceABBA,version]
});
the console shows the correct string, but update function doesn't read mapA value but executes with string 'mapA'.
Upvotes: 3
Views: 1493
Reputation: 83058
You can do:
await amisA.update({
[`amis.${numeroSender}`] : [connaissanceABBA, version]
});
In ES6 (and therefore in TypeScript as well) you can use ComputedPropertyName as shown in the Language Specification: http://www.ecma-international.org/ecma-262/6.0/#sec-object-initializer
Note that in ES5 you would have to do as follows, using the square brackets notation:
var obj = {};
obj[`amis.${numeroSender}`] = [connaissanceABBA, version];
amisA.update(obj);
Note also that this will work as expected with the update()
method since "fields can contain dots to reference nested fields within the document". However, the resulting object in the JavaScript code may not be exactly what you expect. You can see it by doing:
var obj1 = {
[`amis.${numeroSender}`] : [connaissanceABBA, version]
}
console.log(JSON.stringify(obj1));
Finally note that template literals are enclosed by back-ticks, like:
`amis.${numeroSender}`
and not like:
'amis.${numeroSender}'
as shown in your question.
Upvotes: 5