簡體   English   中英

Firestore 從一個文檔中獲取值並更新另一個文檔上的現有值

[英]Firestore get value from one document and update an existing value on another document

我無法從 Firestore 中的文檔字段獲取單個值。 檢索后,我需要將其設置為 Firestore 中另一個文檔的另一個字段。

客戶數:6客戶數:6

import firebase from "firebase/app";
import "firebase/firestore";

const db = firebaseApp.firestore();
const customerCount = db.collection("customers").doc("--stats--");
const customersCollection = db.collection("customers");
const customerRef = customersCollection.doc(docRef.id);
const batch = db.batch();
batch.update(customerRef, {
  customerCount: //<---get the value from firestore (see uploaded image), and set it here
});
batch.set(customerCount, { customerCount: increment }, { merge: true });
batch.commit();

TIA

您的代碼尚未讀取customerCount文檔。 現在的customerCount只是對文檔的引用,但還不包含數據庫中的任何數據。

customerCount.get().then((doc) => {
  const batch = db.batch();
  batch.update(customerRef, {
    customerCount: doc.data().customerCount + 1
  });
  batch.commit();
});

請注意,這里沒有理由使用批處理操作。 實際上,如果您想確保customerRefcustomerCount文檔始終匹配,則在這種情況下您將希望使用事務

暫無
暫無

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

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