0

I have User and Survey model. Survey model looks like this:

const SurveySchema = mongoose.Schema({
    title: {
        type: String
    },
    options: [{
        value: String,
        votes: [{ type: mongoose.Schema.Types.ObjectId, ref: 'User' }]
    }]
})

So in UserSchema, I wanna make cascade delete, when User deletes his account, I wanna remove him from votes. So I tried with something like this:

UserSchema.pre('remove', function (next) {
    this.model('Survey').update({ options: { $elemMatch: { votes: this._id } } }, { $pull: { votes: this._id } }, {multi: true}).exec();
    next();
});

I know this isn't even close to solution, but just so you can see in which way I'm going.

Wolfdog
  • 567
  • 1
  • 9
  • 20
  • It's close but `exec()` takes a callback or Promise to resolve and the `next()` belongs within that, and not just simply on the next line. A better example actually exists in a [different answer to the accepted on the duplicate](https://stackoverflow.com/a/44347976/2313887) considering that actually shows a `$pull` and resolution within the callback response. – Neil Lunn Jun 14 '18 at 13:18
  • Well, the find query for me is working, it finds all Surveys where user voted, but the pull query isn't working, it does not pull his id from the votes. Can you try and test it? – Wolfdog Jun 14 '18 at 13:49
  • The reason why I put next() on the next line is because I want for that update query to be async, so I don't need to wait for response from it, even if I put next() inside, it still doesn't work – Wolfdog Jun 14 '18 at 13:51

0 Answers0