Javascript删除对象属性不起作用 [英] Javascript delete object property not working

查看:139
本文介绍了Javascript删除对象属性不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在MEAN.js上运行了一些项目,我遇到了以下问题。我想做一些用户的配置文件计算并将其保存到数据库。但是用户模型中的方法存在问题:

I'm running some project on MEAN.js and I've got a following problem. I want to make some user's profile calculation and the save it to database. But there's a problem with method in users 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 will send a password with my changes, it will change credentials, so user is unable to login next time. I want to delete password from user object before save, but I'm not able to do it (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's 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);
};

出了什么问题?为什么呢? e delete方法返回true,但没有任何反应?感谢您的帮助:)

What's wrong? Why the delete method returns true, but nothing happens? Thanks for your help :)

推荐答案

javascript中有一些删除运算符的规则

there are certain rules for delete operator in javascript


  1. 如果属性在严格模式下是自己的不可配置属性,则返回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);

所以,请交叉检查这些点,有关详细信息,您可以阅读链接

so, please cross check these point and for more information your can read this Link

这篇关于Javascript删除对象属性不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆