在我尝试在/ users /上查找用户文档进行身份验证后,我想使用来自auth对象的数据以及一些自定义用户属性来更新文档。但我收到更新方法不存在的错误。有没有办法更新单个文档?所有firestore doc示例都假设您拥有实际的文档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"})
});
})
答案 0 :(得分:10)
检查用户是否已经在那里,然后只是.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);
});
答案 1 :(得分:9)
您可以从doc.id
:
var db = firebase.firestore();
db.collection("users").where("uid", "==", payload.uid)
.get()
.then(function(querySnapshot) {
querySnapshot.forEach(function(doc) {
console.log(doc.id, " => ", doc.data());
// Build doc ref from doc.id
db.collection("users").doc(doc.id).update({foo: "bar"});
});
})
答案 2 :(得分:3)
在原始代码中更改此行
doc.update({foo: "bar"})
对此
doc.ref.update({foo: "bar"})
应该工作
,但是更好的方法是使用批量写入: https://firebase.google.com/docs/firestore/manage-data/transactions#batched-writes
答案 3 :(得分:1)
你只需要找到文件的官方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
)