从猫鼬的"toJSON"支持中删除一个属性 [英] remove one property from mongoose 'toJSON' support

查看:67
本文介绍了从猫鼬的"toJSON"支持中删除一个属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am using mongoose's toJSON support as below:

userSchema.set('toJSON', { getters: true, virtuals: true, minimize: false })

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

now in the returned result from a mongoose object's toJSON() method call, I want to remove certain sensitive fields. How to do that?

以不同的方式解释问题:

In different way to explain the issue:

某些字段,例如密码",令牌",我们只需要在查询中使用,而在返回结果中则不需要,如何隐藏它们以防各种查询返回?

Some certain fields like 'password', 'token' which we would need only in query, but not in returned result, how to hide them from returning from all kind of queries?

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

Update: This finally what I ended up with and working like a charm:

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

推荐答案

您可以像这样自定义toJSON在您的架构上的工作方式:

you can customize how toJSON works on your schema like this:

/**
  * 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;
    }
};

doc是要序列化的文档,ret是将转换为JSON的普通JS对象.然后,您可以根据需要操作ret.

doc is the document to be serialized, ret is the plain JS object that will be transformed into JSON. You may then manipulate ret however you want.

这篇关于从猫鼬的"toJSON"支持中删除一个属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆