Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

Updating document within find

Updating document within find

Problem

I'm having issues updating a document from within a find using Mongoose. The issue is only when I attempt to overwrite the document with an Object (e.g doc = req.body). I am however able to directly set properties of the original document to a specific string (e.g. doc.name = 'jason borne';).

I've verified that res.body is an object, so I don't see why I'm unable to set it this way.

Client.findById(req.params.client_id, function (err, client) {

    if (err)
        return next(new restify.InternalError(err));

    // client.name = 'jason borne';

            client = req.body;

    client.save(function(err) {

        if (err)
            return next(new restify.InternalError(err));

        res.send(client);

    });

});

When attempting to set the doc to an object, I receive the error:

TypeError: Object # has no method 'save'

I'm aware that I can do an update with a simple Client.update(...) command, however this method does not allow my schema middleware or validation to run (which is notated in the Mongoose documentation).

Any thoughts? I'm new to Node, and Mongoose.

Problem courtesy of: Nick Parsons

Solution

You need to use something like underscore's extend method to copy the properties of req.body into the client object instead of just re-pointing client to req.body as you are now.

var _ = require('underscore');
Client.findById(req.params.client_id, function (err, client) {

    if (err)
        return next(new restify.InternalError(err));

    _.extend(client, req.body);
    client.save(function(err) {
        if (err)
            return next(new restify.InternalError(err));
        res.send(client);
    });
});
Solution courtesy of: JohnnyHK

Discussion

View additional discussion.



This post first appeared on Node.js Recipes, please read the originial post: here

Share the post

Updating document within find

×

Subscribe to Node.js Recipes

Get updates delivered right to your inbox!

Thank you for your subscription

×