Skipper Lin
Skipper Lin

Reputation: 75

Mongodb updated password is not saved into the database

I am working on a functionality that allows users to update their password. However, the hashed password is not updated into the mongodb database for some reasons.

This is my front end code for updateProfile:

    updateProfile() {
        const modified_auth={
            name: this.state.name,
            email: this.state.email,
            nid: this.state.nid,
            password: this.state.password,
        }

        axios.post('http://localhost:4000/userprofile/update', modified_auth)
            .then(res =>{
                console.log(res.data);
            })
            .catch(err => {console.log('Err' + err);});
    }

This is my back end route to update the user profile:

router.route('/update').post((req,res) => {
    console.log(req.body);
    Auth.findOne({
        $or: [
            { email: req.body.email },
            { nid: req.body.nid }
        ]
    })
    .then(auth => {
        auth.name = req.body.name;
        auth.nid = req.body.nid
        auth.email = req.body.email;
        console.log(auth.password);
        bcrypt.genSalt(10, (err, salt) => {
            bcrypt.hash(req.body.password, salt, (err, hash) => {
                if (err) throw err;
                auth.password = hash;
                console.log(auth.password);
            });
        });
        console.log(auth.password);
        auth.save()
            .then(() => res.json('Auth updated!'))
            .catch(err => res.status(400).json('Error: ' + err));
    console.log(auth.password);
    })
    .catch(err => res.status(400).json('Error: ' + err));
});

I put in a few print statements. Those are what I got back:

$2a$10$uKeVPatEK3QqpvtdjvQYaeELnrAfuOlOhbG/4lJBV8brqLzcU5enW
$2a$10$uKeVPatEK3QqpvtdjvQYaeELnrAfuOlOhbG/4lJBV8brqLzcU5enW
$2a$10$uKeVPatEK3QqpvtdjvQYaeELnrAfuOlOhbG/4lJBV8brqLzcU5enW
$2a$10$K8eKneNAxYC2Xrym3eSXM.xas0ZrmIDVUe8WnmmghgvmzT.uw5l/e

I could not figure out why the new password was not saved into the database.

Thank you so much for the help.

Upvotes: 0

Views: 462

Answers (1)

cischa
cischa

Reputation: 424

Notice that the password generation happens asynchronously alongside the Document save() call. Since the intended behavior is to include the new password in the document update, you can place the save() call inside of the callback for the password generation to ensure that the new document has the updated password:

        bcrypt.genSalt(10, (err, salt) => {
            bcrypt.hash(req.body.password, salt, (err, hash) => {
                if (err) throw err;
                auth.password = hash;
                console.log(auth.password);
                auth.save()
                    .then(() => res.json('Auth updated!'))
                    .catch(err => res.status(400).json('Error: ' + err));
            })
        })

Upvotes: 1

Related Questions