Exclude fields from beeing saved in node mongodb native

Problem

I'm inserting documents using node mongodb native driver into a mongodb (sic!). My objects look like this:

var x = {
  field: 'value',
  _nonPersistentField: 'Do not save that'
};

What I want to achieve is, to prevent all fields prefixed with an underscore not to be saved. In the example above '_nonPersistentField' should not be saved.

Is there a way (except Object.defineProperty) to prevent these fields from being saved in node mongodb native?

Problem courtesy of: saintedlama

Solution

What about a pre-parser? Instead of using save from the mongo client, use:

function save( obj, callback ) {
    var tmp = {};
    Object.keys( obj ).forEach( function( key ) {
        if ( key.substr( 0, 1 ) !== '_' ) {
            tmp[ key ] = obj[ key ];
        }
    } );

    // Now that the object is filtered, use mongodb's client
    mongodb.save( tmp, callback );
}

Using this way, you're not even seeing the object creation and whatnot, instead of:

mongodb.save( obj, function( err, results ) {
} );

You're using:

save( obj, function( err, results ) {
} );
Solution courtesy of: Florian Margaine

Discussion

There is currently no discussion for this recipe.

This recipe can be found in it's original form on Stack Over Flow.