Reputation: 1343
i want to list of new hashtags (e.g. #love, #goodMorning) in the hashtag collection if they don't exist already also the application supports that any logged in user can write into the database.
The code below can be used if only one user have access to this document.
hashtags=["one","two","three"];
hashtags.forEach(hashtagToAdd => {
this.afs.collection("hashtags").ref
.where("name", "==", hashtagToAdd )
.limit(1)
.get()
.then(result => {
if (result.empty) {
// code to add new hashtag e.g. here hashtagToAdd
} else {
console.log("hashtag is already present");
}
})
.catch(error => {
console.log("error aayo che", error);
});
}
In my case, as multiple users can access and write to it. Now if before fetching the hashtag no such hashtag was found but before adding the hashtag, another user if had added the same hashtag already then duplicate entries can exist. how to avoid this ? also is there any better way to do this for the list of new hashtags ?
Upvotes: 1
Views: 341
Reputation: 1343
I found the solution. it can be easily done by storing the data at a static location. For e.g. to store these info...
hashtags=["one","two","three"];
I will use the structure in firestore like this:
/hashtags/one/{name:one}
/hashtags/two/{name:two}
/hashtags/three/{name:three}
Upvotes: 1