我在Cloud Firestore交易中遇到例外

时间:2019-11-07 22:45:59

标签: firebase flutter dart google-cloud-firestore

我收到一个云Firestore异常,该异常表示“执行事务时出错,在事务中读取的每个文档也必须写入。为空”。仅当我尝试通过用户的电子邮件创建用户文档来运行事务时,才会出现此问题,当它位于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时,上述代码非常有用。 请帮助

1 个答案:

答案 0 :(得分:0)

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

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