MethodOverride PUT 不起作用

MethodOverride PUT not working

我正在使用 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 示例中获取了路由,但找不到 link。我的 app.js 有方法覆盖工作,因为我已经完成了 DELETE 请求。该模型具有正确的字段并具有显示在我的显示页面中的默认测试值。

你是这样称呼的:

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 }...

固定路线如下:

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