Flutter firestore - 检查文档 ID 是否已存在 [英] Flutter firestore - Check if document ID already exists

查看:38
本文介绍了Flutter firestore - 检查文档 ID 是否已存在的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I want to add data into the firestore database if the document ID doesn't already exists. What I've tried so far:

// 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"变量匹配.如果匹配,则不会创建文档.如果不匹配,则应创建一个新文档

The goal is to check all the documents ID in the database and see in any matches with the "varuId" variable. If it matches, the document won't be created. If it doesn't match, It should create a new document

推荐答案

可以使用get()方法获取document<的Snapshot/code> 并使用快照上的 exists 属性来检查文档是否存在.

You can use the get() method to get the Snapshot of the document and use the exists property on the snapshot to check whether the document exists or not.

示例:

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
}

这篇关于Flutter firestore - 检查文档 ID 是否已存在的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆