My goal is to allow users to update existing mongoose documents using a form with method-override package. Despite trying various solutions found on Stackoverflow, I have not been able to resolve my issue. The desired functionality is for the user to view their existing document, submit the form with new values, and have it update the database.
I attempted the solution provided in this post How do I update/upsert a document in Mongoose? among others, but it did not work as expected.
Initially, I set up a route to display the individual document:
// EDIT - edit location route
router.get("/location/:id/edit", function(req, res) {
Location.findById(req.params.id, function(err, foundLocation){
res.render("./locations/edit", {location: foundLocation});
});
});
This leads to a landing page with a form to update the information on that document:
<form action="/location/<%= location._id %>?_method=PUT" method="POST">
<div class="form-group"><input class="form-control" type="text" name="location[name]" ></div>
<div class="form-group"><input class="form-control" type="text" name="location[image]" value="<%= location.image %>"></div>
<div class="form-group"><input class="form-control" type="text" name="location[longDescription]" value="<%= location.longDescription %>"></div>
<div class="form-group"><button class="btn btn-lg btn-primary btn-block">Submit!</button></div>
</form>
The route handling the PUT logic is as follows:
router.put("/location/:id", function(req, res) {
Location.findByIdAndUpdate(req.params.id, req.body.location, {new: true}, function(err, updatedLocation){
console.log(req.body.location);
if(err) {
console.log(err);
res.redirect("/search");
} else {
console.log(updatedLocation);
res.redirect("/location/" + req.params.id);
}
});
});
Although no errors are being thrown by this route, the document is not getting updated. Upon logging req.body.location, I noticed that it was returning undefined. This could potentially be the root of the issue, but I'm not sure how to rectify it.
@Deda this is what is logged in console.log(req.body)
'location[image]':
'https://wekivaisland.com/wp-content/uploads/bartlettimage-4977.jpg',
'location[longDescription]': 'Edited Long Description' }
{ address:
{ street: '51 SW 11th Street Apt. 1537',
city: 'Miami',
state: 'FL',
zip: '12345',
country: 'United States' },
author: { id: 5d081e0afd38374b43ca0c14, username: 'danny' },
rating: 0,
_id: 5d08dd702456a30948947c73,
name: 'Random Place',
image:
'https://2.bp.blogspot.com/-yKPXCFHoNhQ/WPOOwjqA3QI/AAAAAAAABmQ/88DcGs-Cp5oXAv6fA6hn3J7NRUlYBaxgwCLcB/s1600/Screen%2BShot%2B2017-04-16%2Bat%2B11.33.00%2BAM.png',
longDescription: 'Place #2',
shortDescription: 'Place #2',
__v: 0 }
The issue was resolved by simply setting bodyParser extended to true.
Previously, it was
app.use(bodyParser.urlencoded({ extended: false }));
By changing it to the following code below, everything worked smoothly.
app.use(bodyParser.urlencoded({ extended: true }));