How to update fields in Firestore map

时光怂恿深爱的人放手 提交于 2020-12-13 09:35:10

问题


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

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.

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

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

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

Thanks


回答1:


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.



来源:https://stackoverflow.com/questions/56514496/how-to-update-fields-in-firestore-map

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!