Mongoose: updating item through POST JSON

Mongoose: updating item through POST JSON

Problem

I have administation page with editing some model. When I get model I convert it into JSON and get something like this:

{
    "__v": 0,
    "_id": "52d919c7ec31cffc17477767",
    "description": "Hello, teached",
    "points": 1300,
}

Here is my jade template

form(role='form', method='post', action='/admin/item')
            .form-group
                textarea.form-control#result(rows='20', name='result') !{JSON.stringify(item, null, '\t')}
            input.btn.btn-primary(type='submit', value='Send')

Here is my router code

app.post('/admin/item', function (req, res) {
    result = JSON.parse(req.body.result);
    Item.update({_id: result._id}, result, function (err, result) {
        if (err) {
            res.send('error');
        } else {
            res.send(result, 200);
        }
    });
});

And I always get an error, but when I update every field manually, like this:

result = JSON.parse(req.body.result);
Item.update({_id: result._id}, {description: result.description, ...

It magically updates. What I am doing wrong?

Problem courtesy of: user3215609

Solution

You need to delete the _id field from the result object, otherwise Mongoose will assume you are trying to cast the _id field from a string rather than an ObjectID. You will also want to do this because I’m assuming updating the _id every time you update the document is probably not your desired behavior.

EDIT:

Also, if you are using the bodyParser middleware with Express, there is no need to parse the JSON yourself. req.body should return a parsed object literal from the body of your POST request. With that said, change your router to look like this to get things working:

app.post('/admin/item', function (req, res, next) {

  var id = req.body.result._id;
  delete req.body.result._id;

  Item.update({_id: id}, req.body.result, function (err, numAffected) {
    // Do something after update here
  });

});
Solution courtesy of: srquinn

Discussion

Leave a Reply

Your email address will not be published. Required fields are marked *