Nodejs / Mongoose:无法输入HTML表单

时间:2018-03-09 09:37:19

标签: node.js mongodb mongoose

我似乎在使用PUT方法更新数据库中用户配置文件时遇到问题。当我更改当前的电子邮件地址,或填写“关于我”部分时,服务器返回“无法发布/设置”。我希望填写“电子邮件”部分(它不能为空),但“关于我”部分是可选的(它可以是空的)。

我尝试在线搜索,但没有一个答案与我的问题有关。我相信问题在于“路由”部分(HTML和MongoDB架构也被添加供您参考,HTML实际上是EJS模板)。这是我的代码:

HTML:

<form action="/settings?_method=PUT" method="POST">
   <div class="form-row">
     <div class="form-group col">
        <label>First Name</label>
        <input class="form-control" type="text" placeholder="<%= currentUser.firstName %>" readonly>
     </div>
     <div class="form-group col">
        <label>Last Name</label>
        <input class="form-control" type="text" placeholder="<%= currentUser.lastName %>" readonly>
     </div>  
   </div>
   <div class="form-group">
      <label for="exampleFormControlTextarea1">About me</label>
      <textarea class="form-control" name="aboutMe" id="exampleFormControlTextarea1" rows="3"></textarea>
   </div>
   <div class="form-group">
      <label for="exampleInputEmail1">Email address</label>
      <input type="email" class="form-control" name="email" id="exampleInputEmail1" aria-describedby="emailHelp" value="<%= currentUser.email %>">
   </div>
   <div class="form-group">
      <label>Birthday</label>
      <input class="form-control" type="text" placeholder="<%= currentUser.birthday %>" readonly>
   </div> 
   <div class="form-group">
      <label>Gender</label>
      <input class="form-control" type="text" placeholder="<%= currentUser.gender %>" readonly>
   </div> 
   <a href="/" class="btn btn-primary btn-settings" role="button">Cancel</a>
   <button type="submit" class="btn btn-primary btn-settings">Save</button>
</form>

NodeJS路线:

router.put("/", function(req, res){
   var newData = {aboutMe: req.body.aboutMe, email: req.body.email};
   User.findByIdAndUpdate(req.user._id, {$set: newData}, function(err, user){
      if(err){
        res.redirect("back");
      } else {
        res.redirect("/settings");
      }
   });
});

MongoDB架构

var UserSchema  = new mongoose.Schema({
    firstName: {type: String, required: true},
    lastName: {type: String, required: true},
    aboutMe: String,
    email: {type: String, required: true, unique: true},
    birthday: {type: String, required: true}, 
    gender: {type: String, required: true}, 
});

0 个答案:

没有答案