I want to update a single record by _id in a collection in mongoDB.
UPDATE: I changed the res to req (thanks!) and implemented the db.ObjectId() around the objectId I am passing in and now I get a 500 internal server error.
"_id" : ObjectId("54d5296711436278137af74b"),
"username" : "alex",
"email" : "alex@gmail",
"fullname" : "alex man",
"age" : "15",
"location" : "minneap",
"gender" : "mal"
This is my ajax call from the client.
$.ajax({
type: 'PUT',
data: updatedUser,
url: '/users/updateuser/' + globalUserID,
dataType: 'JSON'
}).done(function(response){
This is the routing code.
/*
* PUT to updateuser
*/
router.put('/updateuser/:id', function(req, res) {
var db = req.db;
var userToUpdate = req.params.id;
db.collection('userlist').update(
{ _id: userToUpdate},
req.body,
function(err, result){
res.send(
(err === null) ? {msg: ''} : {msg: err}
);
});
});
I get a 200 response back but my record is not updated. What is wrong with my syntax?
You need to make sure you're turning the string
_id into an ObjectId
.
Also, you were using res
.body instead of req
.body.
router.put('/updateuser/:id', function(req, res) {
var db = req.db;
var userToUpdate = req.params.id;
db.collection('userlist').update({ _id: ObjectId(userToUpdate)}, req.body, function (err, result) {
res.send(
(err === null) ? {msg: ''} : {msg: err}
);
});
});
Different drivers use a different method to create an ObjectId:
idString
); idString
); idString
); idString
); It should be req.body, not res.body
db.collection('userlist').update(
{ _id: userToUpdate},
res.body -> should be req.body
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.