MethodOverride PUT无法正常工作

时间:2017-11-05 15:52:08

标签: javascript node.js mongodb express x-http-method-override

我正在使用Node.js,Express和MethodOverride尝试让表单更新模型的一部分(我的用户模型)。

用户模型:

var userSchema = new mongoose.Schema({

email: { type: String, unique: true, lowercase: true },
  password: String,

  profile: {
    name: { type: String, default: 'Company Name' },
    location: { type: String, default: 'Location' },
    website: { type: String, default: 'Your Website' },
    picture: { type: String, default: '' }
  },

  assetNumPre: { type: String, default: 'test' }, // this is the one I want to change

});

module.exports = mongoose.model('User', userSchema);

HTML表单:

<form role="form-inline"action="/dashboard/settings/assetNumber?_method=PUT" method="POST">
 <div class="col-md-3">
   <div class="form-group">
     <label for="prefix" class="control-label">Prefix for Asset Number</label>
     <br>
     <small>Any alphanumeric characters to a limit of 6</small>
     <input type="text" class="form-control" id="prefix" name="prefix" placeholder="Prefix max 6 characters" maxlength="6" value="{{ prefix }}">
   </div><!-- Prefix for Asset Number-->
   <br>
   <div class="box-footer">
     <button type="submit" class="btn btn-primary">Submit</button>
   </div>
  </div>
</form>

然后路线:

app.put('/dashboard/settings/assetNumber',
setRender('dashboard/settings/assetNumbers'),
setRedirect({auth: '/login'}),
isAuthenticated,
dashboard.getDefault,
(req, res) => {
var prefix = req.body.prefix;
console.log(req.params);
User.findByIdAndUpdate({_id: req.params.user_id}, prefix, function(err, UpdatedUser) {
  if (err) {
    res.send(err);
  }
  console.log(UpdatedUser);
  });
res.locals.prefix = req.user.assetNumPre;
});

我的路线遗失的一件事是req.user.assetNumPre,我需要保存它,但我不知道如何执行此PUT请求。文档也没有多大帮助。

我几天前从Stack Overflow示例中获取了该路由,但找不到它的链接。我的app.js方法覆盖工作,因为我已经完成了DELETE个请求。该模型具有正确的字段,并具有显示在我的显示页面中的默认测试值。

2 个答案:

答案 0 :(得分:1)

你在说这个:

User.findByIdAndUpdate({_id: req.params.user_id}, prefix...

但前缀只是值:

var prefix = req.body.prefix;

findByIdAndUpdate takes an Object,而非值,用于更新特定字段。

所以试试:

User.findByIdAndUpdate({_id: req.params.user_id}, { assetNumPre: prefix }...

答案 1 :(得分:0)

这是固定路线:

app.put('/dashboard/settings/assetNumber',
    setRedirect({auth: '/login', success: '/dashboard/settings/assetNumber', failure: '/dashboard/settings/assetNumber'}),
    isAuthenticated,
    (req, res) => {
      User.findById(req.user.id, function(err, user) {
      if (err) return (err);
      user.assetNumPre = req.body.prefix || 'pre';

      user.save(function(err) {
        if (err) return (err);
          req.flash('success', { msg: 'Asset Number Prefix updated.' });
          res.redirect(req.redirect.success);
      });
    });

    res.locals.prefix = req.user.assetNumPre;
    });

所以改变了一些不属于问题的事情。我想我需要在回调函数中设置数据。然后做一个user.save