Jim*_*nes 18 firebase google-cloud-firestore
在进行身份验证后,我正在尝试在/ 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"})
});
})
Run Code Online (Sandbox Code Playgroud)
Ped*_* GM 31
-- 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
});
Run Code Online (Sandbox Code Playgroud)
Jua*_*ara 23
您可以从以下位置构建doc引用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"});
});
})
Run Code Online (Sandbox Code Playgroud)
R..*_*... 13
在您的原始代码中更改此行
doc.update({foo: "bar"})
Run Code Online (Sandbox Code Playgroud)
对此
doc.ref.update({foo: "bar"})
Run Code Online (Sandbox Code Playgroud)
应该管用
但更好的方法是使用批量写入:https : //firebase.google.com/docs/firestore/manage-data/transactions#batched-writes
Ron*_*ton 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);
});
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
37841 次 |
最近记录: |