首页 文章

MongoDB无法更新文档,因为_id是字符串,而不是ObjectId

提问于
浏览
7

我正在做一个休息api来在mongo数据库和web应用程序之间交换数据 . 这些数据是json格式的 .

在更新文档时我遇到了麻烦:

cannot change _id of a document.

事实上,在我的JSON中,doc的_id存储为字符串并反序列化为字符串 . 而它在mongo中存储为 ObjectID . 这解释了为什么mongo会引发错误 .

  • 在mongo中:_id:ObjectId('51051fd25b442a5849000001')

  • 在JSON中:_id:"51051fd25b442a5849000001"

为避免这种情况,我手动将_id属性从 string 转换为 ObjectID . 但它似乎很难看,并且会因其他BSON类型而失败 .

Q: Is there a clean way to avoid that or to do a nice JSON/BSON conversion?

下面是我用来更新文档的代码 . 我正在使用带有express和mongodb的nodejs和本机驱动程序 .

exports.updateById = function(req, res) {
var id = req.params.id;
var map = req.body;

map._id = new ObjectID.createFromHexString( map._id); // Manual conversion. How to avoid this???

console.log( 'Updating map: ' + id);
console.log( 'Map: ' + JSON.stringify( map));

db.collection('maps', function(err, collection) {
    if(err) throw err;
    collection.update(
        {'_id': new BSON.ObjectID(id)}, map, {safe:true}, 
        function(err, result) {
            if (err) {
                console.log('Updating map err: ' + JSON.stringify( err));
                res.json( 500, {'message':'An error has occurred while updating the map', 'error': err});
            } else {
                console.log('Updating succeed');
                res.send(map);
            }
        }
    );
});

};

1 回答

  • 10

    因为您无法修改 _id 字段,所以更好的方法是从 map 对象中删除该字段,而不是将其转换为ObjectId .

    所以这:

    delete map._id;
    

    而不是这个:

    map._id = new ObjectID.createFromHexString( map._id);
    

    如果要返回更新的对象,就像使用 res.send(map); 一样,您应该使用findAndModify而不是 update ,这样您就可以访问生成的文档,而不仅仅是发布的内容 .

相关问题