0

I have to delete URL after certain time (ex: 1 minute) automatically and remove it from user document also.

urlSchema:

const urlSchema = new mongoose.Schema({
    url: {
        type: String,
    },
    user: {
        type: mongoose.Schema.Types.ObjectId,
        ref: 'User'
    },
    expireAt: {
        type: Date,
        default: Date.now,
        index: { expires: 60 },
    },
}

userSchema:

const userSchema = new mongoose.Schema({
        name: {
            type: String,
        },
        urls:[
         {
            type: mongoose.Schema.Types.ObjectId,
            ref: 'Url'
         }
        ],
  }

It is removing url document after 60sec, for removing its reference from user document I tried middleware but it is not triggering.

urlSchema.post("remove", async function(next){
    console.log("In remove")
    const user = await User.findById(this.user);
    if(user){
        user.urls.pull(this._id);
        await user.save();
    }
    next();
})

Tried both "pre" and "post" middleware but they are not running.

Any way to solve this and delete url from user.urls

Harshil Sharma
  • 101
  • 1
  • 2
  • 8

0 Answers0