Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

278
Views
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": "abc@gmail.com",
            "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,

over 4 years ago · Santiago Trujillo
2 answers
Answer question

0

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.

over 4 years ago · Santiago Trujillo Report

0

here is an example using Aggregation

const allMedia = await Media.aggragate([
  $lookup: {
    from: 'uploadedBy',
    localField: 'uploadedBy',
    foreignField: '_id',
    // your variable
    as: 'uploadedBy',
  },
  {
    $project: {
//removing the field you want to remove by attibuting a Zero
      resetPasswordToken:0,
      resetPasswordExpire: 0,
      otp:0,
      otpExpire:0
      // select the field you want to display 
      fieldYouWantoToDisplay: 1,
    },
  },
])
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!