Flutter / Dart 如何检查 Firestore 中是否存在文档?

18

我尝试使用bool查询在cloudfirestore上是否存在文档,但不幸的是,我的代码没有起作用。

我尝试了以下方法,但bool值并未改变。

getok() {
  bool ok;
  Firestore.instance.document('collection/$name').get().then((onexist){
      onexist.exists ? ok = true : ok = false;
    }
  ); 
  if (ok = true) {
    print('exist');
  } else {
    print('Error');
  }
}

可能是因为你设置了true而不是进行比较。 - Clevino Alrin
7个回答

42

使用 Flutter / Dart 编写异步 / 等待函数来检查 Firestore 中是否存在文档

您可以调用的简单异步 / 等待函数以检查文档是否存在。返回 true 或 false。

bool docExists = await checkIfDocExists('document_id');
print("Document exists in Firestore? " + docExists.toString());

/// Check If Document Exists
Future<bool> checkIfDocExists(String docId) async {
  try {
    // Get reference to Firestore collection
    var collectionRef = Firestore.instance.collection('collectionName');

    var doc = await collectionRef.document(docId).get();
    return doc.exists;
  } catch (e) {
    throw e;
  }
}

1
发现当文档ID不存在时,它并不返回false,而是会抛出错误! - Richie
2
刚刚检查过了,如果文档不存在,它会返回false。 - Mahesh Jamdade
当它捕获到一个错误时会发生什么,布尔值会返回一个错误还是假? - Dalon
1
@Dalon,它会抛出一个错误。doc.exists将返回true或false,catch处理与Firestore通信的错误。如果你希望程序在假设为false的情况下继续运行(因此只需在catch中始终返回false),或者你想以另一种方式处理错误(比如显示自定义错误消息),那就由你决定了。 - Matthew Rideout

21

虽然我使用 IDS,但你可以尝试用这种方式做。

//Declare as global variable

bool exist;

static Future<bool> checkExist(String docID) async {       
    try {
        await Firestore.instance.document("users/$docID").get().then((doc) {
            exist = doc.exists;
        });
        return exist;
    } catch (e) {
        // If any error
        return false;
    }
}

6

你可以尝试这个方法,它对我有效

Future getDoc() async{
   var a = await Firestore.instance.collection('collection').document($name).get();
   if(a.exists){
     print('Exists');
     return a;
   }
   if(!a.exists){
     print('Not exists');
     return null;
   }

  }

1
首先,您需要等待答案;其次,您总是可以从数据库中获得答案。这意味着 onexists 总是存在。
您可以通过 .documentID 检查文档是否存在。类似这样:
try {
  var res = await Firestore.instance.document('collection/$name').get();
  print(res.documentID ? 'exists' : 'does not exist');

} catch (err) {
  print(err);
}

0

这个答案检查文档是否存在,如果存在则寻求使用新数据更新它。下面的示例代码是用Flutter(Dart)编写的。

Future uploadDataToFirestore(String docID) async {
var docSnapshot = await checkIfDocExist(docID);
if(docSnapshot.exists){
  try {
    await docSnapshot.reference.update(newData.toMap());
  } catch (e) {
    // TODO: Handle catched error here
  }
}
else{
  // TODO: execute some code here
}

}

Future<DocumentSnapshot<Object?>> checkIfDocExist(String docID) async { try {

  var doc = await collectionRef.doc(docID).get();
  return doc;
} catch (e) {
  rethrow;
}

}


0

  Future<bool> documentExistsInCollection(String collectionName, String docId) async {
    try {
      var doc =
          await FirebaseFirestore.instance.collection(collectionName).doc(docId).get();
      return doc.exists;
    } catch (e) {
      throw e;
    }
  }

0

您可以使用此方法来检查特定集合中是否存在该文档:

 // check if ID exist
  Future checkDocuement(String docID) async {
    final snapShot = await FirebaseFirestore.instance
        .collection('collectionName')
        .doc(docID) // varuId in your case
        .get();

    if (snapShot == null || !snapShot.exists) {
      // docuement is not exist
      print('id is not exist');
    } else {
      print("id is really exist");
    }
  }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接