如何使用mongo,passport和node js更新用户的个人资料?

时间:2017-07-10 14:45:07

标签: node.js mongodb mongoose passport.js

我正在创建一个个人项目。我选择Passport.js进行身份验证,我想使用这个mongoose架构更新用户的个人资料:

var userSchema = mongoose.Schema({
local            : {
    email        : {type: String, required: true, unique: true},
    password     : {type: String, required: true}
},
first_name       : {type: String, required: true},
last_name        : {type: String, required: true},
username         : {type: String, required: true, unique: true},
email            : {type: String, required: true, unique: true}});

这里是我使用的 post 路由:

app.post('/editProfile', isLoggedIn, function(req, res, next){
    User.update({ _id: req.user.id}, req.body, function(err, user){
        if(!user){
            req.flash('error', 'No account found');
            return res.redirect('/edit');
        }
        var emailEdit = req.body.email;
        var usernameEdit = req.body.username;
        var first_nameEdit = req.body.firstname;
        var last_nameEdit = req.body.lastname;
        if(emailEdit.lenght <= 0 || usernameEdit.lenght <= 0 || first_nameEdit.lenght <= 0 || last_nameEdit.lenght <= 0){
            req.flash('error', 'One or more fields are empty');
            res.redirect('/edit');
        }
        else{
            user.email = emailEdit;
            user.local.email = emailEdit;
            user.first_name = first_nameEdit;
            user.last_name = last_nameEdit;
            user.username = usernameEdit;

            res.redirect('/profile/');
        }
    });

当我运行它时,我有一个错误,我不明白为什么

  

TypeError:无法设置属性&#39; email&#39;未定义的

因为user.local.email = emailEdit;当我对此行发表评论时,只会更新用户名。

我确定这是我犯过的一个愚蠢的错误,但我无法找到它。

我还在寻找使用passport,node和mongo更新配置文件的最有效方法。如果可能的话,还有一个动态的,例如,我可以实时检查是否已经使用了用户名,并在这种情况下将字段设置为红色。

2 个答案:

答案 0 :(得分:2)

Model.update的回调不会返回文档。

在您的情况下,我只会使用findByIdsave

app.post('/editProfile', isLoggedIn, function(req, res, next){

    User.findById(req.user.id, function (err, user) {

        // todo: don't forget to handle err

        if (!user) {
            req.flash('error', 'No account found');
            return res.redirect('/edit');
        }

        // good idea to trim 
        var email = req.body.email.trim();
        var username = req.body.username.trim();
        var firstname = req.body.firstname.trim();
        var lastname = req.body.lastname.trim();

        // validate 
        if (!email || !username || !firstname || !lastname) { // simplified: '' is a falsey
            req.flash('error', 'One or more fields are empty');
            return res.redirect('/edit'); // modified
        }

        // no need for else since you are returning early ^
        user.email = email;
        user.local.email = email; // why do you have two? oh well
        user.first_name = firstname;
        user.last_name = lastname;
        user.username = username;

        // don't forget to save!
        user.save(function (err) {

            // todo: don't forget to handle err

            res.redirect('/profile/');
        });
    });
});

答案 1 :(得分:0)

const updateUser = (req ,res, next)=>{
    const updateData = req.body.update;
    if (!updateData){
        res.status(422).send({"message":"please provide what you want to update"})
    }
    User.findOne({email:req.body.user.email}).then(function(user) {
        if (!user) { return res.sendStatus(401); }

        //NOTE  only update fields that were actually passed...
        if (typeof updateData.username !== 'undefined') {
            user.username = updateData.username;
        }
        if (typeof updateData.email !== 'undefined') {
            user.email = updateData.email;
        }
        if (typeof updateData.first_name !== 'undefined') {
            user.email = updateData.email;
        }
        if (typeof updateData.last_name !== 'undefined') {
            user.email = updateData.email;
        }
        if (typeof updateData.bio !== 'undefined') {
            user.bio = updateData.bio;
        }
        if (typeof updateData.image !== 'undefined') {
            user.image = updateData.image;
        }
        if (typeof updateData.password !== 'undefined') {
            user.setPassword(updateData.password);
        }
        return user.save()
            .then(function() {
                return res.json({ user: user.toAuthJSON() });
            });
    }).catch(()=>{
        res.status(422).send({"message":"couldn't update user"})
    }
    );
};
UserSchema.methods.generateJWT = function() {
var today = new Date();
var exp = new Date(today);
exp.setDate(today.getDate() + 60);
return jwt.sign({
    id: this._id,
    username: this.username,
    exp: parseInt(exp.getTime() / 1000),
}, config.secret);

};

UserSchema.methods.toAuthJSON = function() {
return {
    username: this.username,
    email: this.email,
    token: this.generateJWT(),
    bio: this.bio,
    avatar: this.image
};

};