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

查看:73
本文介绍了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()文档,并使用快照上的 exists 属性检查文档是否存在。

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

示例:

final snapShot = await Firestore.instance
  .collection('posts')
  .document(docId)
  .get()

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

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

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