0

我正在使用上述技术构建我的第一个应用程序。在过去的几周里,我一直在使用 Backbone,现在我正在尝试使用带有 mongo db 的 node 上的 express 构建一个 api。(注意,我现在只是使用本机节点 mongo 模块。)

当我用来自 mongo 的数据填充我的骨干集合时,默认情况下它带有 _id 字段。在我尝试更新 mongo 中的文档之前,这不是问题。Backbone 将 _id 作为字符串传回,它应该是一个对象 id。Mongo 更新失败,因为它认为我正在尝试更改您不允许执行的 _id。这是我用数据更新 mongo 的函数的副本。

exports.updateMenu = function(req, res) {
var id = req.params._id;
var item = req.body;

db.collection('menu', function(err, collection) {
    collection.update({'_id':new BSON.ObjectID(id)}, item, {safe:true}, function(err, result) {
        if (err) {
            console.log('Error updating menu: ' + err);
            res.send({'error':'An error has occurred'});
        } else {
            console.log('' + result + ' document(s) updated');
            res.send(item);
        }
    });
});

}

这是我得到的错误。如您所见,我提供的带有 _id 的文档正试图将 _id 更改为字符串。

更新菜单时出错:MongoError: cannot change _id of a document old:{ id: 1, name: "Hotdog", cost: 2.99, description: "Large Beef hotdog with your selection of cheese and sauce", category: "food", _id: ObjectId('51645e0bd63580bc6c000001') } new:{ id: "1", name: "Hotdog", cost: "77", description: "Large Beef hotdog with your selection of cheese and sauce", category: "食物" ,_id:“51645e0bd63580bc6c000001”,错误:“发生错误”}

4

1 回答 1

2

尝试从项目中删除 _id 成员。所以前 3 行应该变成以下 4 行:

exports.updateMenu = function(req, res) {
    var id = req.params._id;
    var item = req.body;
    delete( item._id );
于 2013-04-11T11:18:56.460 回答