unsafe_where_true
unsafe_where_true

Reputation: 6300

mongo: updating a document by id

OK this should be fairly simple so I think I may be doing a thinking mistake.

I have an existing document. I serve it to the client, together with its ObjectId. The client modifies, and wants to update the document. So it comes with the id - looks to me a good choice to identify which document I want to update (?).

But I get an error: [MongoError: Mod on _id not allowed]

This is the code which updates (via HTTP PUT):

     id = req.body._id
     Item.update({'_id': id }, req.body, (err) ->

Upvotes: 0

Views: 214

Answers (1)

Peter Lyons
Peter Lyons

Reputation: 145994

So you need to remove the _id key from the "update" object you send. _.omit can facilitate this.

Item.update {_id: req.body._id}, _.omit(req.body, '_id'), (err) ->

Aside: I see people code like this often. Taking input from the browser and just shoving it into your database is a terrible idea from a data integrity and security perspective. Just like most businesses don't just leave their accounting ledgers out on the counter with a pen and ask the customers to write in there unsupervised. Consider enforcing your data schema, authorization, and some validations.

Upvotes: 2

Related Questions