简体   繁体   中英

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

I am having trouble getting a single value from a field of a document within Firestore. Once retrieved, I then need to set it to another field of another document within Firestore.

customerCount: 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

Your code is not reading the customerCount document yet. The customerCount right now is just a reference to the document, but doesn't contain any data from the database yet.

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

Note that there's no reason to use a batch operation here. In fact, if you want to make sure the customerRef and customerCount documents always match, this is a case where you'll want to use a transaction instead.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM