Ajax DELETE Query Returning Unexpected Object - javascript

My delete controller and AJAX Query are passing unexpected results in data.
I have the following in my AJAX request:
var endpoint = '/api/places/'+$(this).attr('id');
$.ajax({
method: 'DELETE',
url: endpoint,
dataType:"json",
data: $(this).serializeArray(),
success: deletePlace,
error: handleError
});
where endpoint is a valid URL and the same URL in my controller, shown here:
app.delete('/api/places/:id', function deletePlace(req, res) {
// remove place
db.Place.remove({ _id: req.params.id }, function(err, removePlace){
if (err) { throw (err) };
res.json(removePlace);
});
The data passed into deletePlace is "Object {ok: 1, n: 1}" when I am expecting it to be the JSON of the removed Place. Please excuse my novice but I have been wracking my brain on this. Have searched so many posts on here and still can't find the answer.

Only .remove will not return deleted document.
So You've to use .findByIdAndRemove method.
Please read api carefully: http://mongoosejs.com/docs/api.html#model_Model.findByIdAndRemove
Here is the fix:
app.delete('/api/places/:id', function deletePlace(req, res) {
// remove place
db
.Place
.findByIdAndRemove(req.params.id,
function(error, deletedDocument) {
if (error) {
return
res
.status(500)
.send({
success: false,
error: error,
data: {}
});
}
res
.send({
success: true,
data: deletedDocument
});
});
});

Related

How to send a parameter (id) in a $ajax http get request?

Scenario
I've had a problem for 4 hours, I'm trying to send an http get request while sending the user ID as a parameter. I try a lot of examples found on the net but I still have this error on the backend side.
GET http://localhost:3000/api/users/getusersbyid/?userId=00c1308a-32ad-48a0-8737-d4682b2b504e 500 (Internal Server Error)
Here is my JS function code:
async function getUserById() {
try {
await $.ajax({
type: "GET",
url: "http://localhost:3000/api/users/getusersbyid",
data: {
userId: "00c1308a-32ad-48a0-8737-d4682b2b504e"
},
contentType: "application/x-www-form-urlencoded"
}).done(function(response) {
console.log(response);
}).fail(function(err) {
console.log(err);
});
} catch (error) {
console.log(error);
}
}
Here is my Backend function code using NodeJs:
getUserById: function(req, res) {
let userId = req.body.userId;
models.User.findOne({
where: {
id: userId
},
include: [{
model: models.TypeUser,
attributes: ['code', 'value']
}]
}).then(function(data) {
if (data) {
res.status(201).json({
'status': 'success',
'code': 201,
'data': data
});
} else {
res.status(404).json({
'status': 'falled',
'code': 404,
'message': 'Unable to find one or more users'
});
}
}).catch(function(err) {
res.status(500).json({
'status': 'falled',
'code': 500,
'message': 'An internal error has occurred',
'data': err
});
});
}
Here is my Backend Error Message image:
Need your help and suggestions
It seems something's going on in your backend. Have you tried using logging, for example after your "let userId = req.body.userId;" line to see if your server is receiving the userId?
console.log("backend received userId="+userId)
I just solved the problem after reading the answers from #AbhishekKumawat and from #Pointy. So using the "GET" method, I should do this:
let userId = req.query.userId;
instead.
let userId = req.body.userId;

How to return database data in HTTP get method

In server side,I fetch data from database
var sql = require('mssql');
app.get('/api/comments', function(request, response) {
var sqlConfig = {
// Connection string parameters.
}
sql.connect(sqlConfig, function() {
var request = new sql.Request();
var stringRequest = 'select TOP 10 * from comment';
request.query(stringRequest, function(err, recordset) {
if(err) console.log(err);
sql.close();
response.json(recordset);
});
});
});
Then,I fetch the data from server side by AJAX (get method)
_fetchComments() {
jQuery.ajax({
method: 'GET',
url: '/api/comments',
success: (comments) => {
this.setState({ comments })
}
});
I get an error when I get the data by Ajax.
(Uncaught TypeError: this.state.comments.map is not a function)
It seems that the data return is undefined.Instead of fetching database,the code is work if I use static data(hard code) in server side.
I think the problem is the callback function in sql.connect() but I have no idea how to solve it.Does anyone can help?
Error:
The solution is adding dataType: 'json' to the ajax
_fetchComments() {
jQuery.ajax({
method: 'GET',
url: '/api/comments',
dataType: 'json',
success: (comments) => {
this.setState({ comments })
}
});
}

Unexpected Token U Ajax Syntax Error

I've been having a problem all day sending json data via ajax to Express.
My ajax looks like this:
$('#saveClause').click(function () {
var username = document.getElementById('postUserName').innerHTML;
var clauseTitle = document.getElementById('modalTitle').innerHTML;
var clauseDescription = document.getElementById('modalDescription').innerHTML;
var clauseText = document.getElementById('modalText').innerHTML;
$.ajax({
url: "/classes/updateAssignment",
type: "post",
dataType: "json",
data: {
username: username,
title: clauseTitle,
description: clauseDescription,
text: clauseText
},
cache: false,
contentType: "application/json",
complete: function () {
console.log("complete");
},
success: function () {
console.log("success");
},
error: function () {
console.log("Process Error");
}
});
});
and my Express Classes routes looks like this:
router.post('/updateAssignment', function (req, res) {
console.log(req.body.username)
console.log(req.body.title);
console.log(req.body.description);
console.log(req.body.text);
res.type('json');
res.send({
some: JSON.stringify({
response: 'json'
})
});
});
I issued a postman post request to the url with this JSON object:
{
"username":"testing",
"title":"123",
"description":"j456",
"text":"seven"
}
and Express logged all the details in the console just fine, so it must be a problem with my ajax request as it's giving me an unexpected token u error but I don't know what's causing it. Any ideas?
Try removing the contentType: "application/json",
If you used postman with no headers, most likely this is causing the parser to fail.

How Can I Use .find() To Find Documents in DB For Logged In User?

On the backend I have this for my 'get' request to my '/logs' collection. The data comes back as an array called "times":
router.get('/', (req, res) => {
time
.find({'userName': req.params.userName})
.exec()
.then(times => {
console.log(req.params.userName)
//console.log(times)
res.json({
times: times.map(
(time) => time)
});
})
.catch(
err => {
console.error(err);
res.status(500).json({message: 'Internal server error'});
});
});
I am trying to display times for which ever user is logged in and I can do that however the network tab still shows all times for all users instead of the user who is logged in. I have this on the front end making the request:
function getTimesFromDB(callback) {
var user = state.loggedIn;
$.ajax({
type: 'GET',
dataType: 'json',
url: '/logs',
'headers': {
"content-type": "application/json",
},
'data': {
'userName': user,
},
success: callback,
})
}
Any help would appreciated. thanks!
Are you getting the correct value in req.params.userName?
Can you try using req.query.userName instead.

Can't update name in mongo using PUT in node express

I am having trouble updating a name in mongodb. The name is first saved by the user in a variable and passed into a function like this: putAjax(editName) Then it goes to the function here:
function putAjax(editName) {
$.ajax({
type: "PUT",
url: "/items/"+ editName,
data: editName,
dataType: 'json',
})
.done(function(result) {
console.log("result:", result);
console.log("data successfully saved:");
})
.fail(function(jqXHR, error, errorThrown) {
console.log(jqXHR);
console.log(error);
console.log(errorThrown);
});
};
I can console.log(result) and I can see the edited name so I assumed that the edit took place. Finally it makes the call to app.put on the server:
app.put('/items/:name', function(req, res) {
Item.find(req.params.name, function(err, items) {
if (err) {
return res.status(404).json({
message: 'Internal Server Error'
});
}
Item.findOneAndUpdate({
name: req.params.name
}, {
$set: {
name: req.params.name
}
}, { new: true },
function () {
res.json(items);
});
});
});
This is where the update doesn't seem to happen. When I use mongo shell, the one document I have still continues to have the same name and not the edited name. The confusing part is, why does console.log(result) show me the edited name then. I would really appreciate any help on this. Thanks.
You aren't passing a unique key to the database query. You're intention is to change the name stored in the database for an existing record but you're not doing this. Instead you are attempting to find a record that matches the new name value and you always return the value you have sent to the server.
Instead you need to pass a unique identifier with the AJAX request, using the URL makes the most sense.
function putAjax(id, editName) {
var payLoad = { name: editName };
$.ajax({
type: "PUT",
url: "/items/"+ id,
data: payLoad,
dataType: 'json',
})
.done(function(result) {
console.log("result:", result);
console.log("data successfully saved:");
})
.fail(function(jqXHR, error, errorThrown) {
console.log(jqXHR);
console.log(error);
console.log(errorThrown);
});
};
Server side code:
app.put('/items/:id', function(req, res) {
var data = req.body; // data should be validated
Item.findOneAndUpdate({ _id: req.params.id }
, { $set: data }
, { returnOriginal: false }
, function (err, result) {
if (err) {
return res.status(500).json({
message: 'Internal Server Error.'
});
}
return res.json(result);
}
);
});

Categories