Inactive Javascript Object Property

I am running some project on MEAN.js and I have the following problem. I want to do some calculations of the user profile and save it in the database. But the problem with the method in the user model:

UserSchema.pre('save', function(next) {
    if (this.password && this.password.length > 6) {
        this.salt = new Buffer(crypto.randomBytes(16).toString('base64'), 'base64');
        this.password = this.hashPassword(this.password);
    }
    next();
});

If I send the password with my changes, it will change the credentials, so the user will not be able to log in next time. I want to remove the password from the user object before saving, but I can not do this (let's look at the comments in my code below):

exports.signin = function(req, res, next) {
    passport.authenticate('local', function(err, user, info) {
        if (err || !user) {
            res.status(400).send(info);
        } else {
            /* Some calculations and user object changes */
            req.login(user, function(err) {
                if(err) {
                    res.status(400).send(err);
                } else {
                    console.log(delete user.password); // returns true
                    console.log(user.password); // still returns password :(
                    //user.save();
                    //res.json(user);
                }
            });
        }
    })(req, res, next);
};

What happened? Why does the delete method return true, but nothing happens? Thanks for the help:)

+10
source share
3 answers

delete javascript

  • " ", false.

x = 42;         // creates the property x on the global object
var y = 43;     // creates the property y on the global object, and marks it as non-configurable

// x is a property of the global object and can be deleted
delete x;       // returns true

// y is not configurable, so it cannot be deleted                
delete y;       // returns false 
  1. , . .

function Foo(){}
Foo.prototype.bar = 42;
var foo = new Foo();

// returns true, but with no effect, 
// since bar is an inherited property
delete foo.bar;           

// logs 42, property still inherited
console.log(foo.bar);

, ,

+10

:

user.password = undefined;

:

delete user.password;

.

+2

. delete " " . Lodash unset:

_.unset(user, "password");

https://lodash.com/docs/4.17.11#unset

Otherwise, the operator deleteworks. Just in case, the deleteoperator’s documents are here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/delete

0
source

Source: https://habr.com/ru/post/1612444/


All Articles