首页 文章

使用express和node.js更新mongodb中的单个记录

提问于
浏览
1

我想通过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回复,但我的记录没有更新 . 我的语法有什么问题?

2 回答

  • 1

    您需要确保将 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 );

  • 1

    它应该是req.body,而不是res.body

    db.collection('userlist').update(
    { _id: userToUpdate},
       res.body -> should be req.body
    

相关问题