【问题标题】:Why cant I delete an item in an object using `delete`为什么我不能使用“删除”删除对象中的项目
【发布时间】:2019-12-14 14:43:35
【问题描述】:
  static profile = async (req: Request, res: Response) => {
    try {
      const { username } = req.params;
      const account = await userModel
        .findOne({ 'shared.username': username })
        .exec();
      if (account) {
        delete account.shared.email; // <======= Why isnt this deleteing email
        console.log(account.shared);
        res
          .status(200)
          .send({ shared: account.shared, lastSeen: account.updatedAt });
      } else res.status(400).send({ message: 'Server Error' });
    } catch (error) {
      res.status(400).send({ message: 'Server Error', error });
    }
  };

console.log(account.shared) 显示如下

{ language: 'en',
  loggedIn: true,
  warningMessage: 'verify',
  username: 'bill',
  email: 'bill@gmail.com',   // <===== Why is this still here?
  fullName: 'Bill',
  location: '/contact',
  gender: 'male',
  avatarId: '338fcdd84627317fa66aa6738346232781fd3c4b.jpg',
  country: 'US' }

如果我愿意

console.log(account.shared.email); // undefined

我收到undefined,但如果我在前端使用 console.log(response),电子邮件仍然在对象中

【问题讨论】:

标签: node.js express mongoose


【解决方案1】:

你可以像这样使用 ES6 语法来省略它

if (account) {
        const {email, ...otherFields} = account.shared;
        console.log(otherFields);
        res
          .status(200)
          .send({ shared: otherFields, lastSeen: account.updatedAt });
      } else res.status(400).send({ message: 'Server Error' });
    }

【讨论】:

  • 这个很好用,可以用来移除多个键吗?
  • 是的。任何你想从你的对象中省略的东西你都可以用这样的方式解构 const {email, username, nalguage, otherFields} = acount.shared ...
  • 另外,如果我的回答解决了您的问题,您能否将其标记为已解决? :)
  • 那么就像从account 拿走你想要的东西,就像email,name,etc... 一样,然后离开休息?
【解决方案2】:

您声明了const account,可能是因为将帐户声明为常量会阻止delete 更改对象。尝试改用var account

【讨论】:

  • 好的,打电话我确实尝试了let,但它仍然没有删除
猜你喜欢
  • 2016-05-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-03-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多