从mongoose'toJSON'支持中删除一个属性

Ran*_*ana 4 mongoose mongodb

我正在使用mongoose的toJSON支持,如下所示:

userSchema.set('toJSON', { getters: true, virtuals: true, minimize: false })
Run Code Online (Sandbox Code Playgroud)

现在在mongoose对象的toJSON()方法调用的返回结果中,我想删除某些敏感字段.怎么做?

以不同的方式解释问题:

某些字段,如'password','token',我们只需要查询,但不返回结果,如何隐藏它们从所有类型的查询返回?

更新:这最终是我最终得到的并且像魅力一样工作:

userSchema.options.toJSON = {
    getters: true,
    virtuals: true,
    minimize: false,
    transform: function (doc, ret, options) {
      delete ret.password
      delete ret.authToken
      return ret
    }
  }
Run Code Online (Sandbox Code Playgroud)

Ret*_*eto 8

您可以自定义如何在您的架构上使用JSON:

/**
  * adjust toJSON transformation
  */ 
mySchema.options.toJSON = {
    transform: function(doc, ret, options) {
        ret.id = ret._id;
        delete ret.password;
        delete ret.token;
        delete ret._id;
        delete ret.__v;
        return ret;
    }
};
Run Code Online (Sandbox Code Playgroud)

doc是要序列化的文档,ret是将转换为JSON的普通JS对象.然后你可以操纵ret你想要的.