0

So I have this object I get from mongoose, it's a user. I want to delete the hashed password field but I can't seem te remove it.

Tried the following:

apiRoutes.get('/user/:id', function(req, res, next) {
  User.findById(req.params.id, function(err, post) {
    if (err) return next(err);
    delete post['password'];
    res.json(post);
  });
});

There's definitely a password field there, when I debug/console.log the object it prints out the password.

EDIT: Solved it by passing an option to the mongoose call:

User.findById(req.params.id, '-password', function(err, post) { /* ... */ });

But still doesn't explain why delete doesn't work?

Mr. Polywhirl
  • 42,981
  • 12
  • 84
  • 132
RandomPerson
  • 790
  • 2
  • 8
  • 29
  • Just guessing here, but should it be `post.password` instead of `post['password']`? – B_CooperA Feb 02 '17 at 14:33
  • 2
    What does `post.hasOwnProperty('password')` return? Could be that it's an ancestor object that has the password property... – Strille Feb 02 '17 at 14:34
  • @B_CooperA That doesn't matter, tried both – RandomPerson Feb 02 '17 at 14:34
  • Is the object sealed? Object.seal() – GibboK Feb 02 '17 at 14:35
  • @B_CooperA it should not make a difference; some object properties can be marked as "undeletable". Try to deep-copy the object and remove the password from the copy. For deep-copy I use JSON.parse(JSON.stringify(object)), turns out it's the fastest :) – Octav Zlatior Feb 02 '17 at 14:36
  • Also, delete has a return value, you could try to check that. – Octav Zlatior Feb 02 '17 at 14:37
  • To check for properties of object properties, try console.log( Object.getOwnPropertyDescriptor(post, 'password' )); – Octav Zlatior Feb 02 '17 at 14:39
  • Here's an alternative solution: http://stackoverflow.com/a/12096922/2411636 With this, you can exclude the password field from output within the model schema. – B_CooperA Feb 02 '17 at 14:39
  • Regarding GibboK's comment, this shows how Object.seal() prevents delete operations: var test = (seal) => { var o = {a:1, b:2}; if (seal) { console.log("sealing"); Object.seal(o); } console.log("before del", o); console.log("del result", delete o.b); console.log("after del", o); }; test(true); test(false); – mab Feb 02 '17 at 14:42

1 Answers1

0

It seems like the object that mongoose returned wasn't an actual javascript object.

I had to convert it to an object in order to use basic functions on it:

apiRoutes.get('/user/:id', function (req, res, next) {
User.findById(req.params.id, function (err, post) {
    if (err) return next(err);
    post.toObject();
    delete post.password;
    res.json(post);
});
RandomPerson
  • 790
  • 2
  • 8
  • 29