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

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

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;

JSON Load from link to use in scope

I'm using request module in express to load a json from a link.
var url = 'https://api.github.com/users/google/repos';
request.get({
url: url,
json: true,
headers: {'User-Agent': 'request'}
}, (err, res, data) => {
if (err) {
console.log('Error:', err);
} else if (res.statusCode !== 200) {
console.log('Status:', res.statusCode);
} else {
// data is already parsed as JSON:
console.log(data.length);
}
});
The output of console.log returns a length of 30.
How can i use the parsed JSON globally (data), outside the function? If i use console.log(data.length) outside it says
Cannot read property 'length' of undefined
Thank you!
You can do it like this
function AnyFunction(res){
//do what you want here
console.log(res.length);
}
const options = {
method: 'GET',
uri: 'https://api.github.com/users/google/repos',
json: true,
headers: {'User-Agent': 'request'}
}
​
request(options)
.then(function (response) {
// Request was successful, use the response object at will
console.log(response.length);
//you can also pass it in a function and do whatever you want
AnyFunction(response);
})
.catch(function (err) {
// Something bad happened, handle the error
console.log('Error:', err);
})

How to get a browser alert message with angularjs and nodemailer

I am trying to get an alert with after sending an email with nodemailer and not just the json response. Here is what I have so far:
app.js (nodejswith nodemailermodule):
transporter.sendMail(mailOptions, (error) => {
if (error) {
res.sendStatus(500)
} else {
res.sendStatus(200)
}
transporter.close();
});
});
angularjs:
$http.post({
url: '/contactUs',
data: '',
}).then(
function successCallback(response) {
$scope.alert("Message Sent!!")
},
function errorCallback(response) {}
)
you'll need to just call alert("Message Sent") instead of $scope.alert("Message Sent").
If you want it to be angularized, you can inject $window and call $window.alert("Message Sent") which will make it easier on you if you're unit testing.

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.

Ajax DELETE Query Returning Unexpected Object

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

Categories