使用mongodb更新用户模型

时间:2017-04-08 08:12:51

标签: mongodb express routes updatemodel

我很难在更新路线中提取用户ID。我有以下更新表格:

<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=PUT" 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>

我的用户架构是:

var UserSchema = new mongoose.Schema({
username: String, 
password: String,
image: String,
email: String
});

我尝试申请的路线是:

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

我也尝试过将此作为POST请求,但在我提交表单的两种情况下都会出现以下错误:

  throw er; // Unhandled 'error' event
  ^

TypeError: Cannot set property 'username' of null
at /home/ubuntu/workspace/NUFC/NUFC_Blogv1.2/routes/index.js:89:15
at Query.<anonymous>    (/home/ubuntu/workspace/NUFC/NUFC_Blogv1.2/node_modules/mongoose/lib/model.js:3701:16)
at /home/ubuntu/workspace/NUFC/NUFC_Blogv1.2/node_modules/mongoose/node_modules/kareem/index.js:273:21
at /home/ubuntu/workspace/NUFC/NUFC_Blogv1.2/node_modules/mongoose/node_modules/kareem/index.js:127:16
at _combinedTickCallback (internal/process/next_tick.js:73:7)
at process._tickCallback (internal/process/next_tick.js:104:9)

0 个答案:

没有答案