'deleting a document by updating it and the problem with unique fields

I have a user schema that has an email field, the email field must be unique.

However, the problem is that when someone wants to delete a user, my code does not actually delete the user, but rather, it sets a field named "_archived" to true.

The problem is that when a user gets 'deleted' (i.e. updated to set the _archived field to true), the email gets reserved for the deleted account. In other words, no body can use that email address afterwards because it's unique.

How to work around this in mongoose?



Solution 1:[1]

I suggest you to keep a status field in the user schema.

const userSchema = new mongoose.schema({
  email: {
   type: String,
   // Note that I haven't added `unique: true` here. 
   // because that will create an index in the DB. And not a validator.
 },
 status: {
   type: String,
   enum: ['active','deleted'],
   default: 'active'
 }
})

Now when you need to create a user you will create it after checking if email already exists.

const isEmailUsed = UserModel.findOne({email:'[email protected]'})
if(!isEmailUsed) await UserModel.create({email:'[email protected]'})
else throw new Error('email is used')

After deleting the user set status to deleted.

UserModel.findOneAndUpdate({email:'[email protected]', status: 'deleted'})

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 shubham