简体   繁体   English

如何更新Firestore地图中的字段

[英]How to update fields in Firestore map

Don't know how to go about adding new fields into a map in Firestore using a variable rather then a hardcoded field name. 不知道如何使用变量而不是硬编码的字段名称将新字段添加到Firestore中的地图中。

I have a data structure in firestorm. 我在风暴中有一个数据结构。 The collection is called webQuiz and the document is called '12345. 该集合称为webQuiz,文档称为'12345。 The data structure looks like: 数据结构如下:

    roomName: Demo0
    roomNumber: 46532
    people:{11111:"David, 22222:"Peter}

Note that people is a map data object. 请注意,人是地图数据对象。

I would like to add another field to the people map. 我想在人员地图中添加另一个字段。 The code below works but instead of the data looking like people:{11111:"David, 22222:"Peter, 44444:"Cathy"} it looks like people:{11111:"David, 22222:"Peter, x:"Cathy"} 下面的代码有效,但不是看起来像people:{11111:"David, 22222:"Peter, 44444:"Cathy"}的数据people:{11111:"David, 22222:"Peter, 44444:"Cathy"}看起来像people:{11111:"David, 22222:"Peter, x:"Cathy"}

How can I use a variable which holds the field name in this situation? 在这种情况下,如何使用保存字段名称的变量? The x should be a variable but it is picked up literally as a property. x应该是一个变量,但实际上是作为属性选择的。

    function testing(){

      var x = "44444"
      var y = "Cathy"

      var cityRef = db.collection('webQuiz').doc('12345');

    var setWithMerge = cityRef.set({
      people: {x: y}
    }, { merge: true });

I expect the output in firestorm to be people: {11111:"David, 22222:"Peter, 44444:"Cathy"} but the actual output at the moment is people: {11111:"David, 22222:"Peter, x:"Cathy"} 我希望在风暴中的输出为人员: {11111:"David, 22222:"Peter, 44444:"Cathy"}但目前的实际输出为人员: {11111:"David, 22222:"Peter, x:"Cathy"}

Thanks 谢谢

You'll need to use the full field path as the key of the update: 您需要使用完整的字段路径作为更新的关键:

var setWithMerge = cityRef.set({
  `people.${x}`: y
});

This will prevent re-writing the entire "people" field, since you are specifying which property of the map to change directly. 由于您要指定直接更改地图的属性,因此这将防止重新编写整个“人”字段。

Note that the field name and the property name are separated by a period. 请注意,字段名称和属性名称由句点分隔。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM