Update user schema using mongodb

express
nodejs
mongodb

#1

I’m creating a blog app using express and mongodb and I’m struggling to get my update route working for my user model.

I have an update form which is as follows:

<div class="row">

<div id="user-image-preview" class="col-md-4 col-sm-12 user-image-preview"></div>

<div class ="reg-container-form col-md-8 col-sm-12">

<div class="jumbotron form"><h2><i class="fa fa-user-plus" aria-hidden="true"></i> Update profile</h2></div>
<form id="register" action = "/update-user" method="POST">
<div class="form-group has-feedback">
    <i class="fa fa-user" aria-hidden="true"></i>
    <label for="username">Username</label>
        <input id="username" type = "text" class = "form-control" value = "<%=currentUser.username%>" name="username"> 
</div>

<div class="form-group has-feedback">
    <i class="fa fa-envelope" aria-hidden="true"></i>
    <label for="email">Email</label>
        <input id="email" type = "email" class = "form-control" value = "<%=currentUser.email%>" name="email"> 
</div>

<div class="form-group">
    <div><i class="fa fa-picture-o" aria-hidden="true"></i>  <label for="img">Image</label></div>
        <input id="user-image-set" type = "text" class ="form-control" placeholder = "Enter image URL" name = "image">
          <a href="#"><div id="eye-button"><i id="preview-icon" class="fa fa-eye" aria-hidden="true"></i></div></a>
</div>

    <button id="submit-login" type ="submit">Confirm changes</button>
</form>
</div>
</div>

This form is accessed through the following route:

router.get("/profile", function(req, res){
res.render("profile")
})

The POST route I am trying to get to work is:

router.post(’/update-user’,function (req,res,next){

User.findOne({_id: req.body._id},function (err,user){
user.username = req.body.username;
user.email = req.body.email;
user.image = req.body.image;
user.save()
if(err){
res.redirect("/profile")
} else {
res.redirect("/blogs")
}}
)});

However, when I try to run this I get an error saying:

Cannot set property 'username' of null

I presume there’s a problem with my code when trying to extract the current user id? I tried re-factoring this using the findByIdAndUpdate method as follows:

router.post("/update-user", function(req, res, next){
User.findByIdAndUpdate(req.body.user_id, req.body.user, function(err,updatedUser){
    if(err){
        res.redirect("/profile")
        console.log(err);
    } else {
        res.redirect("/blogs");
    }
})
})

This code runs without error and does successfully redirect me to the /blogs page, but doesn’t update the user Schema. I’m guessing I’m missing an updatedUser.save() or something similar, however when I added this it also threw an error (cannot save undefined)… very lost on this! If anyone can help would be ace