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

t4n*_*3d3 7 javascript json mongodb node.js bson

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

更新文档时遇到麻烦:

cannot change _id of a document.
Run Code Online (Sandbox Code Playgroud)

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

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

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

问:有没有一种干净的方法可以避免这种情况或做一个不错的JSON/BSON转换?

下面是我用来更新文档的代码.我正在使用带有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);
            }
        }
    );
});
Run Code Online (Sandbox Code Playgroud)

};

Joh*_*yHK 10

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

所以这:

delete map._id;
Run Code Online (Sandbox Code Playgroud)

而不是这个:

map._id = new ObjectID.createFromHexString( map._id);
Run Code Online (Sandbox Code Playgroud)

如果你想要像你正在尝试的那样返回更新的对象res.send(map);,那么你应该使用findAndModify而不是update这样,你可以访问生成的文档,而不仅仅是发布的内容.