簡體   English   中英

Flutter Firestore 更新在哪里

[英]Flutter Firestore Update Where

我正在嘗試運行一個查詢,該查詢在給定 where 子句的情況下檢索單行並更新它。 我了解 Firebase 不支持UpdateWhere操作,因此我嘗試改用Transaction

我很難讓它工作,也許我太習慣 sql dbs ......這是我的壞代碼

try {
    final whereQuery = _db
        .doc(userPath(user))
        .collection("someInnerCollection")
        .where("active", isEqualTo: true)
        .limit(1);

    await _db.runTransaction((transaction) async {
        final entry = await transaction.get(whereQuery);  // This doesn't compile as .get doesn't take in a query
        await transaction.update(entry, {
            "someValue": "newValue",
        });
    });
} catch (e) {
    ...
}

您在update()操作中將DocumentSnapshot傳回,而不是DocumentReference本身。 嘗試像這樣重構:

final docRefToUpdate = _db.collection("colName").doc("docId");

await _db.runTransaction((transaction) async {
  final entry = await transaction.get() // <-- DocRef of document to update in get() here
  await transaction.update(docRefToUpdate, {
    // Pass the DocumentReference here ^^
    "someValue": "newValue",
  });
});

您可以使用集合引用,然后使用.update() 更新單個字段。

final CollectionReference collectionReference = FirebaseFirestore.instance.collection('users');

await collectionReference.doc(user.uid).collection('yourNewCollection').doc('yourDocumentInsideNestedCollection').update({
        'singleField': 'whatever you want,
      });

使用“where”的相同代碼

collectionReference.doc(user.uid).collection('yourNewCollection').doc().where('singleField', isEqualTo: yourValue).update({
            'singleField': 'whatever you want,
          });

根據我所做的測試,我建議以下內容來實現您提到的內容:

基於以下答案

從 API 文檔中可以看到, where()返回查詢object。 它不是文檔參考。

即使您認為查詢只會返回一個文檔,您仍然必須編寫代碼來處理它可能在QuerySnapshot object 中返回零個或多個文檔的事實。 我建議查看有關查詢的文檔以查看示例。

完成查詢咨詢后,您必須獲取該給定結果的DocumentReference

然后,您可以使用該引用來更新批處理寫入中的字段

try {
    final post = await firestore
        .collection('someInnerCollection')
        .where('active', isEqualTo: true)
        .limit(1)
        .get()
        .then((QuerySnapshot snapshot) {
            //Here we get the document reference and return to the post variable.
            return snapshot.docs[0].reference;
        });

    var batch = firestore.batch();
    //Updates the field value, using post as document reference
    batch.update(post, { 'someValue': 'newValue' }); 
    batch.commit();
    
} catch (e) {
    print(e);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM