How do I link the data to the user?
In my case I have a comments section on my blog, where the user can post a comment.
The structure looks something like this:
- posts
- My First Post
- content: "a big string of the post content"
- data: "Date Created"
- image: "Image URL"
- imagecaption: "Image Caption"
- comments
- ???
Now under the comments it would be nice to have something like this:
- comments
- HbsfJSFJJSF (Comment ID)
- user: (User Reference)
- comment: "Nice Blog!"
Now I understand I could so something like this:
- comments
- HbsfJSFJJSF (Comment ID)
- user: user_uid
- comment: "Nice Blog!"
But that has the problem(?) that if the account is deleted (I have that feature), the comment won't be deleted.
Is there a proper way to link the data (comment) to the user such that when the users account is deleted the comment gets deleted, or at least is there a way to delete the comments corresponding to the user when his/her account is deleted?
There is no built-in support in the Firebase Realtime Database for a managed link. So it's up to code that you write.
Frequently this means that you'll have a central function (possibly in Cloud Functions for Firebase) that handles the deletion of a user. This function then calls Firebase Authentication to delete the user, and it updates the database to remove the references to the user.
There is also an open-source project that aims to make this sort of clean-up operation simpler/more reliable: https://github.com/firebase/user-data-protection
Your idea of using user: user_uid
under each comment node would work and is known as denormalisation and fanout .
Using this method, you could cascade deletes by performing a query to obtain all comments where the user
value is equal to the current user's ID, and delete each one, something like:
var commentsRef = firebase.database().ref('comments');
var userId = firebase.auth().currentUser.uid;
commentsRef.orderByChild('user').equalTo(userId).once('value', function(snapshot) {
snapshot.forEach(function(childSnapshot) {
var commentKey = childSnapshot.key;
commentsRef.child(commentKey).remove();
});
});
To ensure this is performed behind the scenes when a user is deleted, you could move the above logic into a Cloud Function that's triggered by a delete request.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.