0

Currently working on a personal website for myself and ran in to some difficulties with mongodb & mongoose when trying to delete a user.

Right now I have two Schema's show below.

UserSchema:

const userSchema = new mongoose.Schema({
    username: {
        type:String,
        required: true,
        unique: true, 
    },
    password: String,
    firstName: String,
    lastName: String,
    eMail: String,
    status: {type:Boolean, default: true},
    hobbies: [
        {
            type: mongoose.Schema.Types.ObjectId,
            ref: "Hobby"
        }
    ]

HobbySchema:

const hobbySchema = new mongoose.Schema({
    title: String,
    user: {
        id: {
            type: mongoose.Schema.Types.ObjectId,
            ref: "User"
            },
        username: String
    },
  
    desc: String,
    iconURL: String
    
});

My issue right now is that when I delete the user using the following route with nodeJS:

 router.delete('/delete/:id', async (req,res) => {
    await User.findOneAndDelete(req.params.id, (err, foundUser) => {
        if(err){
            console.log(err);
        }else{
            res.redirect("/logout"); 
        }
    })
});

I run into the issue that the Hobby collection still contains all hobbies that the user created. I'm looking to have them all deleted when the user wants to delete their account.I understand that Mongodb/Mongoose is a non-relation database and is unlike SQL as I'm coming from SQL. Is there any way to delete all hobbies a user created? (Just creating hobbies as a very basic example).

What is the best alternative? Just going with SQL lite and changing the database entirely?

Thanks

rwright94
  • 45
  • 1
  • 7
  • 2
    Related: https://stackoverflow.com/questions/14348516/cascade-style-delete-in-mongoose – Taplar Oct 15 '20 at 20:34
  • It requires multiple queries on mongodb if you are using multiple collections. At least one to delet e the hobbies, one to delete the user. – Matt Oct 15 '20 at 21:35

0 Answers0