【问题标题】:What is the way to update or insert a record on Firebase with Flutter?使用 Flutter 在 Firebase 上更新或插入记录的方法是什么?
【发布时间】:2022-01-04 21:54:38
【问题描述】:

我有一个这样的集合users

[{
  'uid' : '1',
  'favourites' : [
    { // fav1 },
    { // fav2 },
    { // fav3 },
    etc
  ]
},
{
  'uid' : '2',
  'favourites' : [
    { // fav1 },
    { // fav2 },
    { // fav3 },
    etc
  ]
},
etc
]

在某些情况下,我必须使用新的“fav”更新 favourites 集合,我可以这样做:

final doc = FirebaseFirestore.instance.collection('users').doc(userId);                      
doc.update({ 'favourites': FieldValue.arrayUnion([fav.toJson()]) });

但是该项目可能不存在,所以我必须使用doc.set 来创建一个新项目。由于我是 Firebase 的新手,对于这样的问题,什么是“最佳实践”(如果元素不存在,请先创建它,否则更新它)?

【问题讨论】:

    标签: firebase flutter google-cloud-firestore


    【解决方案1】:

    您可以为set 指定一个合并选项,这正是您想要的:

    doc.set({ 'favourites': FieldValue.arrayUnion([fav.toJson()]) }, SetOptions(merge : true))
    

    【讨论】:

      【解决方案2】:

      您可以使用一个函数来检查是否有包含该特定信息的文档。你可以创建一个 if-else 语句,这取决于是否有一个这样命名的文档。

      检查文档的示例函数:

      Future<bool> checkIfDocExists(String stuffID) async {
            try {
              /// Check If Document Exists
              // Get reference to Firestore collection
              var collectionRef = FirebaseFirestore.instance
                  .collection('favorites');
      
              var doc = await collectionRef.doc(userId).get();
              return doc.exists;
            } catch (e) {
              throw e;
            }
          }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2015-04-19
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-06-05
        • 1970-01-01
        • 2018-10-11
        • 2017-12-19
        相关资源
        最近更新 更多