填充子文档时忽略 toJSON 方法

toJSON method is ignored when populating sub documents

我需要从 JSON 响应中删除某些字段。我已经使用 toJSON() 方法来执行此操作。这是我的模态方法的代码。

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

上面的代码工作正常,但是当我用我的媒体模型填充用户模式时,它不会删除我从 JSON 响应中删除的字段。

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

这是我为使用媒体模型填充用户模型而编写的代码。但问题是用户填充了媒体,但它不会忽略我从 toJSON() 方法中删除的字段。

    {
        "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"
    }

如果有人能提供帮助,我们将不胜感激。

提前致谢,

您可以为 Media 架构的每个查询定义 pre 挂钩。

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');
});

您可以为其他查询添加新的 pre 挂钩,就像 find.

您可以找到更多详细信息 here

这里是一个使用聚合的例子

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,
    },
  },
])