I'm trying to produce a 'catch-all' update POST query for my application.
Basically I need to perform the POST request with an identifier ID and fields to update, and it would update those fields dynamically. Here's what I have so far (in CoffeeScript):
router.post '/update', (req, res) ->
whitelist = ['name', 'price', 'quantity', 'checked']
toUpdate = {}
for attr, val of req.body
if attr in whitelist
toUpdate[attr] = val
if toUpdate.length > 0
(req.db.collection 'products').findAndModify {
query: {_id: req.body.id}
update: {$set: toUpdate}
}
Problem is, I can only pass it strings.
For example, if I wanna update a boolean, I don't know how to enforce the correct type.
POST request:
{ checked: 'true' }
Which will save like so in the database, but what I WANT to have is:
{ checked: true }
So my question is, is there a way to automatically enforce the correct type, so that it will convert by a set of rules I define per field?
Or do I have to code this manually before saving?
I tried looking up creating models in MongoDB, but it's really a big mess, I can't understand anything from the documentation. Google isn't coming up with good results either because I can't really seem to phrase what I want correctly in a search query.