简体   繁体   English

Firestore 从一个文档中获取值并更新另一个文档上的现有值

[英]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.我无法从 Firestore 中的文档字段获取单个值。 Once retrieved, I then need to set it to another field of another document within Firestore.检索后,我需要将其设置为 Firestore 中另一个文档的另一个字段。

customerCount: 6客户数: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 TIA

Your code is not reading the customerCount document yet.您的代码尚未读取customerCount文档。 The customerCount right now is just a reference to the document, but doesn't contain any data from the database yet.现在的customerCount只是对文档的引用,但还不包含数据库中的任何数据。

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.实际上,如果您想确保customerRefcustomerCount文档始终匹配,则在这种情况下您将希望使用事务

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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