如何更新Firestore地图中的字段 [英] How to update fields in Firestore map

查看:36
本文介绍了如何更新Firestore地图中的字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

不知道如何使用变量而不是硬编码的字段名称将新字段添加到Firestore中的地图中.

Don't know how to go about adding new fields into a map in Firestore using a variable rather then a hardcoded field name.

我在风暴中有一个数据结构.该集合称为webQuiz,文档称为'12345.数据结构如下:

I have a data structure in firestorm. The collection is called webQuiz and the document is called '12345. The data structure looks like:

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

请注意,人是地图数据对象.

Note that people is a map data object.

我想在人员地图中添加另一个字段.下面的代码有效,但不是看起来像的数据 people:{11111:"David,22222:" Peter,44444:"Cathy"} people:{11111:"David,22222:" Peter,x:"Cathy"}

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"}

在这种情况下,如何使用保存字段名称的变量?x应该是一个变量,但是从字面上可以看出它是一个属性.

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.

    function testing(){

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

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

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

我希望在风暴中的输出为people: {11111:"David,22222:" Peter,44444:"Cathy"} ,但目前的实际输出是人员: {11111:"David,22222:" Peter,x:"Cathy"}

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"}

谢谢

推荐答案

您需要使用完整的字段路径作为更新的键:

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.

这篇关于如何更新Firestore地图中的字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆