I have a problem with my PUT route, but i do not know exactly what.
First I created my schema:
var databaseSchema = mongoose.Schema({
date: type {
type: Date,
{
_id: String,
});
var Db = mongoose.model('Db', databaseSchema);
After I created a post method:
app.post('/db', function(req, res) {
var body = req.body,
database = new Db(body);
database.save(function (err) {
if (err) {
console.log('err', err);
res.status(500).json(err);
return;
}
res.status(200).json('ok');
console.log('Success');
In my INDEX, I created a GET with Ajax, to display the data in HTML:
$.ajax({
type: 'GET',
url: host + '/db',
success:function(datas){
datas.forEach (function (data) {
var HTML = [];
HTML.push('<tr class="datas">');
HTML.push('<td data-id="' + data._id + '"/> </td>');
HTML.push('</tr>');
$('tbody').append(HTML.join(''));
I created a date in my index, and I'm trying to send it along with the ID to my database, for this I use the PUT method, like this:
$.ajax({
type: 'PUT',
url: host + '/db',
data: {
_id: update.attr('data-id'),
date: $('.date').val();
},
sucess:function (success) {
alert('ok');
},
error:function(err) {
console.log(err);
}
});
Finally I update her on my app.put route, like this:
app.put('/db', function(req, res) {
Reserva.findById(req.param('date'), function(err, database){
database.save(function (req, res) {
if (err) {
console.log('err', err);
}
res.status(200).json('ok');
console.log('Update');
});
});
});
The problem is that the put is not working and I'm not finding the error, could someone give me a light?
Many browsers (even modern) don't support any request methods beyond GET
and POST
. To get these to work, you must do a few things:
Express app:
method-override
package.var methodOverride = require('method-override');
app.use(methodOverride('_method'));
Client-side JS:
Modify your AJAX call to include the _method
field in your data.
$.ajax({
type: 'POST', // Change this to a method everyone understands
url: host + '/db',
data: {
_id: update.attr('data-id'),
date: $('.date').val(), // <- Remove the semicolon that was here
_method: 'PUT'
},
// ...
});