Flutter firestore - 检查文档 ID 是否已存在

2024-04-11

如果文档 ID 尚不存在,我想将数据添加到 firestore 数据库中。 到目前为止我尝试过的:

// varuId == the ID that is set to the document when created


var firestore = Firestore.instance;

if (firestore.collection("posts").document().documentID == varuId) {
                      return AlertDialog(
                        content: Text("Object already exist"),
                        actions: <Widget>[
                          FlatButton(
                            child: Text("OK"),
                            onPressed: () {}
                          )
                        ],
                      );
                    } else {
                      Navigator.of(context).pop();
                      //Adds data to the function creating the document
                      crudObj.addData({ 
                        'Vara': this.vara,
                        'Utgångsdatum': this.bastFore,
                      }, this.varuId).catchError((e) {
                        print(e);
                      });
                    }

目标是检查数据库中的所有文档 ID 并查看与“varuId”变量的任何匹配项。如果匹配,则不会创建该文档。如果不匹配,应该创建一个新文档


您可以使用get()方法得到Snapshot of the document并使用exists快照上的属性来检查文档是否存在。

一个例子:

final snapShot = await FirebaseFirestore.instance
  .collection('posts')
  .doc(docId) // varuId in your case
  .get();

if (snapShot == null || !snapShot.exists) {
  // Document with id == varuId doesn't exist.

  // You can add data to Firebase Firestore here
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Flutter firestore - 检查文档 ID 是否已存在 的相关文章

随机推荐