Search code examples
javascriptnode.jsmongodbexpressx-http-method-override

MethodOverride PUT not working


I am using Node.js, Express and MethodOverride to try and have a form update only 1 part of a model (my user model).

User model:

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:

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

Then route:

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;
});

One thing my route is missing is req.user.assetNumPre which is where I need to save it but I have no clue how to do this PUT request. Docs are not helping much either.

I got the route from a Stack Overflow example a few days ago and can't find the link to it. My app.js had method override working because I have done DELETE requests already. The model has the correct field and has a default test value that shows up in my show page.


Solution

  • You're calling this:

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

    But prefix is only the value:

    var prefix = req.body.prefix;
    

    findByIdAndUpdate takes an Object, not a value, to update a specific field.

    So try:

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