javascript 如何更新单个firebase firestore文档

14ifxucb  于 2023-01-07  发布在  Java
关注(0)|答案(6)|浏览(137)

认证后我尝试在/users/查找一个用户文档,然后我想用auth对象的数据和一些自定义用户属性更新文档。但是我得到一个错误,即update方法不存在。有没有办法更新单个文档?所有的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"})
      });
 })
zf9nrax1

zf9nrax11#

您可以精确地执行以下操作(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'
  });
//....

也可以查看官方文档

plicqrtu

plicqrtu2#

检查用户是否已经在那里,然后简单地.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);
});
dffbzjpn

dffbzjpn3#

--更新防 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
});
raogr8fs

raogr8fs4#

在原始代码中更改此行

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

到这个

doc.ref.update({foo: "bar"})

应该可以
but a better way is to use batch write: https://firebase.google.com/docs/firestore/manage-data/transactions#batched-writes

yr9zkbsy

yr9zkbsy5#

正确的做法如下:要在snapshot对象中执行任何数据操作,我们必须引用.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"})
      });
 })
kzmpq1sx

kzmpq1sx6#

您只需要找到文件的官方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
)

相关问题