使用 express 和 node.js 更新 mongodb 中的单条记录
Update single record in mongodb using express and node.js
我想在 mongoDB 的集合中通过 _id 更新单个记录。
更新:我将 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 条回复,但我的记录没有更新。我的语法有什么问题?
应该是req.body,不是res.body
db.collection('userlist').update(
{ _id: userToUpdate},
res.body -> should be req.body
您需要确保将 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.Types.ObjectId(
idString
);
我想在 mongoDB 的集合中通过 _id 更新单个记录。
更新:我将 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 条回复,但我的记录没有更新。我的语法有什么问题?
应该是req.body,不是res.body
db.collection('userlist').update(
{ _id: userToUpdate},
res.body -> should be req.body
您需要确保将 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.Types.ObjectId(
idString
);