I am building web application to track baseball players.The only data attributes associated with the players currently is fName and lName. I am using Node.js Express 4, mongoose, and Jade. I have the get request functioning properly when you click on a player it will take you to localhost:3000/player/:id with the players information correctly loaded into the view.I am having issues with my post method and getting it to actually update the player information on submit. Instead of updating the player my post method is just adding a new player.
Here is the code for the get request that seems to be functioning properly:
router.get('/:id', function(req,res){
Player.find({_id: req.params.id}, function(err, player){
if(err){
res.redirect('/error');
}else{
res.render(
'editPlayer',
player[0]
);
}
});
});
Here is the code for the post that is creating a new player and not updating the current player:
router.post('/:id', function(req,res){
Player.where({ _id: req.params.id }).update({ fName: req.body.fName, lName: req.body.lName });
res.redirect('player');
});
Here is editPlayer.jade which contains the form I am using to update the player:
extends layout
block content
block content
h1 #{fName} #{lName}
form(method="post" action="/#{_id}")
input(type="hidden" value=_id name="id")
label(for="fName") First Name:
input(type="text", name="fName", value=fName)
label(for="lName") Last Name:
input(type="text", name="lName", value=lName)
input(type="submit", value="Save")
If there is any more information that would be helpful please let me know. Thank you for your time in advance, -fred k
Let's see... don't you want a findOne() call instead of a find() in the router code?
It's probably just that you need to swap req.params.id with req.body.id, btw.
You might try this style in the POST... (noting the use of req.body.id here instead of req.param.id, for example)
router.post('/:id', function(req,res) {
Player.findOne({})
.where('_id').equals(req.body.id)
.exec(function(err, playerRecord) {
if (playerRecord) {
playerRecord.fName = req.body.fName;
playerRecord.lName = req.body.lName;
playerRecord.save();
console.log('player/:id replace successful with Player record');
} else {
console.log('POST player/:id err');
} // End of if (playerRecord)
res.redirect('player');
}); // End of Player.findOne
}); // End of router.post