如何更新单个 firebase firestore 文档

问题描述 投票:0回答:8

身份验证后,我尝试在 /users/ 查找用户文档,然后我想使用 auth 对象中的数据以及一些自定义用户属性来更新文档。 但我收到更新方法不存在的错误。 有没有办法更新单个文档? 所有 firestore 文档示例都假设您拥有实际的文档 ID,并且它们没有任何使用 where 子句进行查询的示例。

firebase.firestore().collection("users").where("uid", "==", payload.uid)
  .get()
  .then(function(querySnapshot) {
      querySnapshot.forEach(function(doc) {
          console.log(doc.id, " => ", doc.data());
          doc.update({foo: "bar"})
      });
 })
javascript firebase google-cloud-firestore
8个回答
127
投票

您可以精确地执行以下操作(https://firebase.google.com/docs/reference/js/v8/firebase.firestore.DocumentReference):

// firebase v8
var db = firebase.firestore();

db.collection("users").doc(doc.id).update({foo: "bar"});

//firebase v9
const db = getFirestore();
async (e) => { //...
 await updateDoc(doc(db, "users", doc.id), {
    foo: 'bar'
  });
//....

也请查看官方文档


33
投票

-- FIREBASE V9 更新 --

在新版本的 Firebase 中,这样做是这样的:

import { doc, updateDoc } from "firebase/firestore"; const washingtonRef = doc(db, "cities", "DC"); // Set the "capital" field of the city 'DC' await updateDoc(washingtonRef, { capital: true });
    

26
投票
检查用户是否已经在那里,然后只需

.update

,或者 
.set
 如果不存在:

var docRef = firebase.firestore().collection("users").doc(firebase.auth().currentUser.uid); var o = {}; docRef.get().then(function(thisDoc) { if (thisDoc.exists) { //user is already there, write only last login o.lastLoginDate = Date.now(); docRef.update(o); } else { //new user o.displayName = firebase.auth().currentUser.displayName; o.accountCreatedDate = Date.now(); o.lastLoginDate = Date.now(); // Send it docRef.set(o); } toast("Welcome " + firebase.auth().currentUser.displayName); }); }).catch(function(error) { toast(error.message); });
    

20
投票
在您的原始代码中更改此行

doc.update({foo: "bar"})
到此

doc.ref.update({foo: "bar"})
应该可以工作

但更好的方法是使用批量写入:

https://firebase.google.com/docs/firestore/manage-data/transactions#batched-writes


3
投票
正确的做法如下; 要在快照对象中进行任何数据操作,我们必须引用 .ref 属性

firebase.firestore().collection("users").where("uid", "==", payload.uid) .get() .then(function(querySnapshot) { querySnapshot.forEach(function(doc) { console.log(doc.id, " => ", doc.data()); doc.ref.update({foo: "bar"})//not doc.update({foo: "bar"}) }); })
    

0
投票
您只需在这里找到文件的官方ID、代码即可!

enter code here //Get user mail (logined) val db = FirebaseFirestore.getInstance() val user = Firebase.auth.currentUser val mail = user?.email.toString() //do update val update = db.collection("spending").addSnapshotListener { snapshot, e -> val doc = snapshot?.documents doc?.forEach { //Assign data that I got from document (I neet to declare dataclass) val spendData= it.toObject(SpendDt::class.java) if (spendData?.mail == mail) { //Get document ID val userId = it.id //Select collection val sfDocRef = db.collection("spendDocument").document(userId) //Do transaction db.runTransaction { transaction -> val despesaConsum = hashMapOf( "medalHalfYear" to true, ) //SetOption.merege() is for an existing document transaction.set(sfDocRef, despesaConsum, SetOptions.merge()) } } } } } data class SpendDt( var oilMoney: Map<String, Double> = mapOf(), var mail: String = "", var medalHalfYear: Boolean = false )
    

0
投票
添加这些答案:如果您无法访问

doc

 并且希望动态地
获取文档。 可悲的是,在

React Native

环境中,我找不到导入

doc
的方法来获取
id
。我正在使用
https://rnfirebase.io/firestore/usage
。对于一些依赖于 Firebase 插件/库的不太常见的环境,情况可能是相同的。
在这种情况下,

console.log(documentSnapshot.ref);

将返回您可以在下面找到的内容。

enter image description here 如您所见,在使用

raw

响应时,可以通过

documentSnapshot.ref._documentPath._parts[1]
访问它。
documentSnapshot
当然是
querySnapshot
的一部分。在问题中,它被称为
doc
现在您可以将其传递给呼叫:

import firestore from "@react-native-firebase/firestore"; // you could have it imported from a different library, but always better to just import firestore rather than entire firebase from which you can (also) get firestore. ... firestore() .collection(YOUR_COLLECTION_NAME) .doc(documentSnapshot.ref._documentPath._parts[1]) // or assign it to a variable, and then use - better .update({...}) .then(() => {}) .catch(() => {}) .finally(() => {});



0
投票
你可以这样尝试。

最新问题
© www.soinside.com 2019 - 2025. All rights reserved.