[英]How to use `onDisconnect()` in Firebase v9 ReactJS?
[英]how to update sub collection's all fields on V9 firebase in reactJs
所以我正在創建 instagram 克隆並在 firebase 文檔中嘗試更新字段:
const uploadPostOnline = (imageUrl, caption) => {
const userRef = doc(db, "users", "posts");
setDoc(
userRef,
{ imageUrl: imageUrl },
{ caption: caption },
{ likes: 0 },
{ likesByUsers: [] },
{ comments: [] },
{ createdAt: serverTimestamp() },
{}
);
};
我希望我的代碼使用我添加的字段為每個用戶創建一個“帖子”集合。
安全規則代碼:
rules_version = '2';
service cloud.firestore {
match /databases/{database}/documents {
function userIsAuthenticated(){
return request.auth != null;
}
match /{path=**}/posts/{postId}{
allow read, write : if userIsAuthenticated();
}
match /users/{userId}{
allow read, write : if userIsAuthenticated();
}
}
}
我希望我的代碼使用我添加的字段為每個用戶創建一個“帖子”集合。
您需要使用用戶的ID在子集合中添加post
文檔,如下:
const userId = ... // For example auth.currentUser.uid (check that value is not undefined, see https://firebase.google.com/docs/auth/web/manage-users#get_the_currently_signed-in_user)
const collectionRef = collection(db, "users", userId, "posts");
addDoc(collectionRef, {
imageUrl,
caption,
likes: 0,
likesByUsers: [],
comments: [],
createdAt: serverTimestamp()
});
setDoc()
將DocumentReference作為第一個參數,將包含文檔所有字段的單個object 作為第二個參數。 嘗試重構代碼,如下所示:
const uploadPostOnline = (imageUrl, caption) => {
const userRef = doc(db, "users", "posts");
setDoc(
userRef, {
// 'imageUrl: imageUrl' is redundant as your property name and var name are name
imageUrl,
caption,
likes: 0,
likesByUsers: [],
comments: [],
createdAt: serverTimestamp()
}
);
};
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.