Reputation: 166
so im creating instagram clone and in the firebase docs trying to update the fields:
const uploadPostOnline = (imageUrl, caption) => {
const userRef = doc(db, "users", "posts");
setDoc(
userRef,
{ imageUrl: imageUrl },
{ caption: caption },
{ likes: 0 },
{ likesByUsers: [] },
{ comments: [] },
{ createdAt: serverTimestamp() },
{}
);
};
this is my firebase database picture:
I want my code to create a collection of "post" for every user with the fields i added.
EDITED: This is the screenshot i got after adding catch
Security Rule Code:
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();
}
}
}
Upvotes: 0
Views: 95
Reputation: 83048
I want my code to create a collection of "post" for every user with the fields I added.
You need to use the ID of the user to add a post
document in a subcollection, as follows:
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()
});
Upvotes: 2
Reputation: 50830
The setDoc()
takes a DocumentReference as first parameter and a single object containing all the fields of your document as second. Try refactoring the code as shown below:
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()
}
);
};
Upvotes: 1