【发布时间】:2013-01-29 14:42:46
【问题描述】:
我正在做一个 rest api 来在 mongo 数据库和 web 应用程序之间交换数据。这些数据是 json 格式的。
我在更新文档时遇到了麻烦:
cannot change _id of a document.
事实上,在我的 JSON 中,文档的 _id 存储为字符串并反序列化为字符串。而它在 mongo 中存储为 ObjectID。这解释了为什么 mongo 会引发错误。
- 在 mongo 中:_id: ObjectId('51051fd25b442a5849000001')
- 在 JSON 中:_id:"51051fd25b442a5849000001"
为避免这种情况,我手动将 _id 属性从 string 转换为 ObjectID。但它看起来很难看,并且会与其他 BSON 类型一起失败。
问:有没有一种简洁的方法可以避免这种情况或进行良好的 JSON/BSON 转换?
下面是我用来更新文档的代码。我将 nodejs 与 express 和 mongodb 与本机驱动程序一起使用。
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);
}
}
);
});
};
【问题讨论】:
标签: javascript json node.js mongodb bson