繁体   English   中英

我怎样才能正确地将 append map 阵列转移到 Firestore?

[英]How can I CORRECTLY append map array to firestore?

我想使用代码将 Map<> 数据添加到我的 firestore 数据库中:

Map<String, Object> prop = {
  'read' : true,
  'vote_left' : false,
  'vote_right' : false,
};
Map<String, Object> attended_topic =
{
  received_id:prop
};

FirebaseFirestore.instance.collection('userinfo').doc(user_now!.uid)
    .update({"attended_topic": FieldValue.arrayUnion([attended_topic])});

我所期待的是这个。

attended_topic
  topicId_0
    read : true 
    vote_left : false
    vote_right : false 

但我得到了一些意想不到的东西。

attended_topic
  0
    topicId_0
      read : true 
      vote_left : false
      vote_right : false 

我从没想过会出现新的“0”类别,也不知道为什么。 由于数据库有其他属性,所以我认为使用update()而不是set()就足够了。 请有人告诉我为什么会这样。

文档FieldValue.arrayUnion将元素添加到数组中,但仅添加尚未存在的元素。

所以{"a": FieldValue.arrayUnion([b])}b变量添加到Array a中。

要解决您的问题,只需删除FieldValue ,如下所示。

FirebaseFirestore.instance
    .collection('userinfo')
    .doc(user_now!.uid)
    .set({"attended_topic": attended_topic}, SetOptions(merge: true));
// use set method to add new data (not update)
// or

FirebaseFirestore.instance.collection('userinfo').doc(user_now!.uid).set(
  {
    'attended_topic': {
      received_id: {
        'read': true,
        'vote_left': false,
        'vote_right': false,
      }
    }
  },
  SetOptions(merge: true),
);

我参考彼得的解决方案解决了这个问题并稍微改变了它。

FirebaseFirestore.instance.collection('userinfo').doc(user_now!.uid)
    .set({"attended_topic": attended_topic}, SetOptions(merge: true));

暂无
暂无

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

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