MongoDB无法更新文档,因为_id是字符串,而不是ObjectId [英] MongoDB can't update document because _id is string, not ObjectId

查看:752
本文介绍了MongoDB无法更新文档,因为_id是字符串,而不是ObjectId的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在做一个REST API,以在mongo数据库和Web应用程序之间交换数据.这些数据是json格式的.

I'm doing a rest api to exchange data between a mongo database and a web app. These data are json formatted.

在更新文档时遇到麻烦:

I have a trouble when it comes to update a document:

cannot change _id of a document.

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

As a matter of fact, in my JSON the _id of the doc is stored as a string and deserialized as a string. Whereas it is stored as an ObjectID in mongo. This explains why mongo raises an error.

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

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

To avoid this I manually convert the _id property from a string to an ObjectID. But It seems ugly and will fail with other BSON types.

问:有没有一种干净的方法来避免这种情况或进行良好的JSON/BSON转换?

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

Below is the code I use to update a document. I'm using nodejs with express and mongodb with the native driver.

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.

Because you can't modify the _id field, a better approach is to simply remove the that field from your map object instead of converting it to an ObjectId.

所以这个:

delete map._id;

代替此:

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

如果要像尝试使用res.send(map);一样返回更新的对象,则应使用

If you want to return the updated object like you're attempting with res.send(map);, you should be using findAndModify instead of update so you have access to the resulting doc and not just what was posted.

这篇关于MongoDB无法更新文档,因为_id是字符串,而不是ObjectId的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆