0
  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) shows the below

{ 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' }

if id do

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

I get undefined but if I console.log(response) on the front end the email is still in the object

Bill
  • 4,614
  • 13
  • 77
  • 132
  • I think this is the reason you are unable to delete it.https://stackoverflow.com/questions/23342558/why-cant-i-delete-a-mongoose-models-object-properties – KrishnaSingh Dec 14 '19 at 15:12
  • It's because of the implementation of mongoose , you can also check delete usage in mozzila doc https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/delete – KrishnaSingh Dec 14 '19 at 15:15

2 Answers2

1

You can omit it using ES6 syntax like this

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' });
    }
Lazar Nikolic
  • 4,261
  • 1
  • 22
  • 46
0

You declared const account, might be that declaring account as a constant prevents the delete to alter the object. Try using var account instead.

mottek
  • 929
  • 5
  • 12