MongoDB不能更新文档,因为_id是string,而不是ObjectId

我正在做一个restapi在mongo数据库和一个web应用程序之间交换数据。 这些数据是json格式。

更新文档时遇到麻烦:

cannot change _id of a document. 

事实上,在我的JSON文档的_id存储为一个string,并作为一个string反序列化。 而它在mongo中作为ObjectID存储。 这就解释了为什么mongo会产生一个错误。

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

为了避免这种情况,我手动将_id属性从一个string转换为一个ObjectID 。 但它看起来很丑陋,并会与其他BSONtypes失败。

问:有没有一种干净的方法来避免这种情况,或者做一个很好的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); } } ); }); 

};

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

所以这:

 delete map._id; 

而不是这个:

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

如果你想返回更新的对象,就像你尝试使用res.send(map); ,您应该使用findAndModify而不是update因此您可以访问生成的文档,而不仅仅是发布的内容。