//User Schema
{ name: String } //_id automatically added by Mongoose
//Post Schema
{ content: String,
comments: [{
date: Date,
user: Schema.ObjectId,
content: String
}]
}
In my application, users will be able to leave comments on particular articles. In my comments schema, I will have an ObjectID referencing the user, so that I can populate his or her username on the front end. However, when the user deletes his or her account, the ObjectIDs in all of the comments they have posted in the past are now meaningless, so I cannot retrieve his or her username to display on the front end. My solution was to initially have a comment reference a user by ObjectID, and then on the pre-delete Mongoose middleware go through all of the comment objects with a matching ObjectID and replace the user
field with a string of their username, so that my front end can still display their name even when their account is deleted.
How would I go about making a field in my Mongoose Schema be valid as either a String or an ObjectID?
Is there a better solution to this problem?
I can suggest you a very simple way to solve the kind of problem you are in. Add a field names status
in your User document. When an user deletes their accounts, you don't delete their account. The reason I am suggesting this is you need the user's detail even after they delete their account. All the users will have active
status for their accounts except those who have deleted their accounts. For the users who have deleted their accounts, have their status as inactive
or archived
. To make sure users with inactive status are not able to perform some actions, kindly make some checks in login about the user status.
Hope this helps.