删除运算符在 node.js 中未按预期运行

delete operator not functioning as expected in node.js

在我的 node.js Express 应用程序中,我正在从我的数据库中检索用户

const newUser = await User.create({
      username,
      password,
      email,
      avatar,
})

但在使用用户对象发送响应之前,我想删除密码。

delete newUser.password;
return res.status(200).json({ token, user: newUser });

但在我的回复中返回了密码。

console.log(JSON.stringify(newUser)) returns:

{"_id":"11111111","username":"dylan","email":"dylan@email.com","admin":true,"password":"******"}

查询return值是文档不是javascript对象

  • 文档有一个 toObject 方法,可以将 mongoose 文档转换为普通的 JavaScript 对象。
  • 首先将其转换为对象,然后在您想要的每个 属性 上使用 delete

还有 mongoose 它可以更准确、更自动地完成

User.methods.toJSON = function () {
  const user = this;
  const userObj = user.toObject();
  delete userObj.password;
  return userObj;
};

每次您将此文档作为响应发送时,它都会转换为 JSON,并且每次 JSON.strigify() 在文档上调用时,它都会调用此 toJSON() 方法

也许你也可以

delete newUser._doc.password