【问题标题】:I'm getting an exception in cloud firestore transactions我在云 Firestore 事务中遇到异常
【发布时间】:2019-11-07 22:45:59
【问题描述】:

我收到一个云存储异常,上面写着“执行事务时出错,事务中读取的每个文档也必须写入。,null”。只有当我试图通过他的电子邮件创建用户文档来运行事务时才会出现此问题,当它在 UID 上时一切正常。

Future<bool> updateFavorites(String email, String recipeId) {
  DocumentReference favoritesReference =
Firestore.instance.collection('users').document(email);
  return Firestore.instance.runTransaction((Transaction tx) async {
DocumentSnapshot postSnapshot = await tx.get(favoritesReference);
if (postSnapshot.exists) {
  if (!postSnapshot.data['favorites'].contains(recipeId)) {
    await tx.update(favoritesReference, <String, dynamic>{
      'favorites': FieldValue.arrayUnion([recipeId])
    });
  } else {
    await tx.update(favoritesReference, <String, dynamic>{
      'favorites': FieldValue.arrayRemove([recipeId])
    });
  }
} else {
  await tx.set(favoritesReference, {
    'favorites': [recipeId]
  });
}
  }).then((result) {
return true;
  }).catchError((error) {
print('Error: $error');
return false;
  });
}

这是发生交易的函数,该函数在这里被调用:

  void handleFavoritesListChanged(String recipeID) {
    updateFavorites(appState.user.email, recipeID) //the user hold the current firebase user
.then((result) {
      if (result == true) {
        setState(() {
        if (!StateModel.favorites.contains(recipeID))
             StateModel.favorites.add(recipeID);
          else
            StateModel.favorites.remove(recipeID); //StateModel is a class which has the empty list of favorites
        });
      }
    });
  }

当我使用 user.uid 而不是 use.email 时,上面的代码效果很好。 请帮忙

【问题讨论】:

    标签: firebase flutter dart google-cloud-firestore


    【解决方案1】:

    我认为应该是string 电子邮件('email')指向下面(已编辑)中的路径,而不是电子邮件对象本身。

    DocumentReference favoritesReference =
    Firestore.instance.collection('users').document('email')
    

    【讨论】:

    • 但是这个东西可以与另一个名为 placeOrder() 的函数一起使用,它具有相同的代码但不检查收藏夹是否包含食谱 ID
    • 所以我想确保在您的 firestore 数据库中,您有一个名为“users”的集合和一个名为“email”的集合之后的文档。以这种方式设置它会很奇怪,但这就是上面的代码读取方式。您可能拥有的是一个用户集合,每个用户都有一个文档,该文档具有到每个用户的某些键:值对的映射。因此,对于上述内容,它将是: Firestore.instance.collection('users').document('jonny123')... 以访问包含用户 Jonny 的电子邮件、用户名等的地图。
    • 我发现主要问题不在于电子邮件,而在于方法 contains(),if(!postSnapshot.data['favorites'].contains(recipeId)),还有另一个函数这类似于我在问题中显示的代码,我在电子邮件上使用的另一个函数并且没有这一行 (if(!postSnapshot.data['favorites'].contains(recipeId)),) 所以这就是问题所在,方法 contains 被调用为 null
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-08-17
    • 1970-01-01
    • 2020-12-03
    • 2011-03-18
    • 1970-01-01
    • 1970-01-01
    • 2020-12-09
    相关资源
    最近更新 更多