我想通过 _id 更新 mongoDB 集合中的单个记录。
更新:我将 res 更改为 req(谢谢!)并围绕我传入的 objectId 实现了 db.ObjectId(),现在我收到 500 内部服务器错误。
"_id" : ObjectId("54d5296711436278137af74b"),
"username" : "alex",
"email" : "alex@gmail",
"fullname" : "alex man",
"age" : "15",
"location" : "minneap",
"gender" : "mal"
这是来自客户端的 ajax 调用。
$.ajax({
type: 'PUT',
data: updatedUser,
url: '/users/updateuser/' + globalUserID,
dataType: 'JSON'
}).done(function(response){
这是路由代码。
/*
* 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}
);
});
});
我收到 200 响应,但我的记录没有更新。我的语法有什么问题?
最佳答案
您需要确保将 string
_id 转换为 ObjectId
。
此外,您使用的是 res
.body 而不是 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}
);
});
});
不同的驱动程序使用不同的方法来创建 ObjectId:
- mongoDB 原生驱动:new ObjectId(
idString
); - mongoJS: db.ObjectId(
idString
); - mongoSkin: toObjectID(
idString
); - Mongoose :mongoose.Types.ObjectId(
idString
);
关于javascript - 使用 express 和 node.js 更新 mongodb 中的单个记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28376058/