Express Auth(权限管理)的设置 (五) 隐藏私有数据

有两种方式,分手动和自动

1. 手动

修改返回 res 的数据,删除 user 中的私有数据

res.send({ user: user.getPublicProfile(), token });
userSchema.methods.getPublicProfile = function() {
  const user = this;
  const userObject = user.toObject();

  delete userObject.password;
  delete userObject.tokens;

  return userObject;
};

2. 自动

修改 userSchema.methods.getPublicProfile 名字为 toJSON

userSchema.methods.toJSON

以下例子可以演示数据操作的过程

当使用 res.send() 的方法时候,自动调用 JSON.stringify() 方法

const pet = {
  name: "Hal",
};

pet.toJSON = function() {
  console.log(this);
  return this;
};

console.log(JSON.stringify(pet));

如果修改了 object 的 toJSON 方法,在使用 JSON.stringify(object) 的时候,将会调用 toJSON 中的代码返回修改后的对象。该例子中将会返回 {}

const pet = {
  name: "Hal",
};

pet.toJSON = function() {
  return {}
};

console.log(JSON.stringify(pet));

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值