I created collection "Users" and I can make CRUD operation, but now I want to make a limit to user to have ability to create one collection, and when it have one, can just update the date.
const URC = collection(db, "Users");
const submitFun = (e) => {
e.preventDefault();
(async () => {
const { name, desc, email, adres, website, phone, photo } =
formData.current;
await addDoc(URC, {
name: name.value,
desc: desc.value,
email: email.value,
adres: adres.value,
website: website.value,
phone: phone.value,
photo: photo.value,
});
})();
};
Do I have to in this function make an if statement?
How to give user.id to this function to work it proper?
2
Answers
Thinking in perspective where email id is unique for users.
One approach , you will have document ids unique. You can get document by email.
You can find more information on setDoc() and query().
Another approach having email as document id. But it is not recommended. Because if application allows email id change , document id should also be changed. And it is better to handle unique objects by id.
There is nothing built in that can help you limit the user to create only one collection. However, that can be solved really simply. You can create a document that can hold an array of UIDs. When a user creates a collection, add the corresponding UID to that array. Each time a user needs to perform such an operation, check that array against the UID. If it is not present, let the user create the collection, otherwise, don’t allow it.
The schema may look like this:
This can be much easier in the Realtime Database, where a possible schema should look like this:
In this way, you should only check if a particular UID exists under
restrictions
node.