toJSON method is ignored when populating sub documents

I need to remove certain fields from the JSON response. I've used the toJSON() method for doing this. Here is the code of my modal method for it.

    User.methods.toJSON = function () {
      let obj = this.toObject()
    
      delete obj.resetPasswordToken
      delete obj.resetPasswordExpire
      delete obj.otp
      delete obj.otpExpire
      return obj
    }

The above code is working fine but when I populate the User modal with my Media model it doesn't remove the fields that I deleted from the JSON response.

    const allMedia = await Media.find({}).populate({
      path: 'uploadedBy', // this is the user document 
    })

This is the code I wrote for populating the user model with the media model. But the problem is User gets populated with Media but it doesn't ignore the fields that I deleted from toJSON() method.

    {
        "name": null,
        "sizes": [],
        "isPrivate": false,
        "_id": "61d6d1a1fcaf7337f6f186de",
        "path": "http://192.168.1.7:2121/uploads/2022/1/7b37e2bc-b313-4b08-abd6-101e99c36527.png",
        "uploadedBy": {
            "firstName": "abc",
            "lastName": "abc",
            "role": "ADMIN",
            "resetPasswordToken": "77bda3f7794d305d7771fc23d932e1e9922df02c71b02c3564ad46b22ceac27e",
            "resetPasswordExpire": "1640954443294",
            "otp": null,
            "otpExpire": null,
            "_id": "61ceea9ce989f2d986fa9c5c",
            "userName": "abc",
            "email": "[email protected]",
            "createdAt": "2021-12-31T11:33:48.066Z",
            "updatedAt": "2021-12-31T13:08:36.245Z"
        },
        "createdAt": "2022-01-06T11:25:21.839Z",
        "updatedAt": "2022-01-06T11:25:21.839Z"
    }

If anyone can help, it would be appreciated.

Thanks in advance,


You can define pre hook for each query for Media schema.

const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const schema = new Schema(...);

schema.pre('find', function () {
  this.populate('uploadedBy');
  this.select('-resetPasswordToken -resetPasswordExpire -otp -otpExpire');
});

You can add new pre hooks for other queries, just like for the find.

You can find more details here.