【问题标题】:Removing specific map/object from array in firebase从firebase中的数组中删除特定的地图/对象
【发布时间】:2019-01-27 21:30:30
【问题描述】:

我正在 Firestore 中试验数组和地图/对象。我想知道如何从数组中删除特定的地图。 我尝试过这样的事情:

await Firestore.instance.collection('users').document(interestedInID).get().then((val){
  return val.data['usersInterested'].removeWhere((item)=>
    item['userID'] == userID
  ); 
}).catchError((e){
  print(e);
});

但我在终端收到此错误:

Unsupported operation: Cannot remove from a fixed-length list

我真的不明白这是什么意思。我做了一些谷歌搜索,固定长度的列表正是它所说的。它是一个具有固定长度且不能更改的列表,但必须明确声明固定长度列表。另一方面,可增长列表不需要声明。 我还没有在我的 firestore 中声明定长列表,但它一直说我不能从中删除元素。但是,我可以添加/推送元素并使用以下方法删除它们:

'key': FieldValue.arrayRemove([value])

但我不知道如何根据特定条件删除元素。在本例中为用户 ID。

有什么建议吗? 非常感谢!

【问题讨论】:

  • 你找到解决这个问题的方法了吗?
  • 嗨@Andrey。很久以前,但我发布了对我有用的解决方案,但它显示我删除了它。我不知道为什么,所以我取消了删除该帖子。你能在下面看到它吗?

标签: firebase dart flutter google-cloud-firestore


【解决方案1】:

想通了。

await Firestore.instance.collection('users').document(interestedInID).updateData({
  'usersInterested': FieldValue.arrayRemove([{}.remove(userID)])
});

我不确定,但我认为 get() 只是允许您阅读文档,但不允许对其进行任何更改。 无论如何,现在它可以工作了

【讨论】:

    【解决方案2】:

    这可能是一种解决方法:

    1. 您使用来自 Firebase 的 key: values 获取您的特定 Array
    2. 将其放在 dart 中的临时引用 List 中
    3. 从引用 List 中删除您的特定 Map,就像以前一样
    4. 像这样更新 Firebase 中的数据:
    // make a reference List
    List<Map> _modifiedUsersInterested = List();
    
    // ... (fetch your Array first from Firebase, put those items in the reference List)
    
    // remove the right Map from the reference List
    _modifiedUsersInterested.removeWhere((item) => {
        item['userID'] == userID
    });
    
    // set the reference List as your array in Firebase
    await Firestore.instance
    .collection('users')
    .document(interestedInId)
    .updateData(
        {'usersInterested': _modifiedUsersInterested}
    );
    

    【讨论】:

    • 您确认此方法有效吗?无论哪种方式,都应该有一种更简单的方法来执行此操作,而无需读取然后重新保存整个列表减去删除的值。
    猜你喜欢
    • 1970-01-01
    • 2019-11-02
    • 2013-12-13
    • 2018-10-03
    • 2011-11-09
    • 1970-01-01
    • 2020-09-11
    • 2019-12-03
    • 2020-10-21
    相关资源
    最近更新 更多