Reputation: 448
I'm building my first app using the above technologies. I've spent the last couple of weeks using Backbone and now I'm trying to build an api using express on node with mongo db. (note, I'm just using the native node mongo module at the moment.)
When I fill my backbone collection with data from mongo, by default it comes with the _id field. Not a problem until I try and update the document in mongo. Backbone passes back the _id as a string and it should be a object id. Mongo fails the update because it thinks I'm trying to change the _id which your not allowed to do. Heres a copy of my function to update mongo with the data.
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);
}
});
});
}
Heres the error I get. As you can see, the document with the _id I've provided is attempting to change the _id to a string.
Error updating menu: MongoError: cannot change _id of a document old:{ id: 1, name: "Hotdog", cost: 2.99, description: "Large Beef hotdog with your choice of cheese and sauce", category: "food", _id: ObjectId('51645e0bd63580bc6c000001') } new:{ id: "1", name: "Hotdog", cost: "77", description: "Large Beef hotdog with your choice of cheese and sauce", category: "food", _id: "51645e0bd63580bc6c000001", error: "An error has occurred" }
Upvotes: 0
Views: 777
Reputation: 471
Try deleting the _id member from item. So the first 3 lines should become the following 4 lines:
exports.updateMenu = function(req, res) {
var id = req.params._id;
var item = req.body;
delete( item._id );
Upvotes: 2