Express and Mongoose based REST API - filter out some properties of an object before returning it to the user

I am building a RESTful API using Express and Mongoose on top of Node.js

I am using certain fields/properties in my Schemas that are reserved for internal use only, they should not be seen by the API users at all.

What is the best way to remove them before I res.send() them? Do I have to do it manually per each route (get, post, update) or is there a general way to filter them out?

I tried using custom middleware, but that did not work - when I placed my middleware before I did use( app.router ) the res.body was undefined, and if i placed it after, my middleware was never called. Also, since in the middleware I am dealing with both single documents and arrays of documents, I'd rather find a way to do it per-document.

You can use the select attribute of a schema field's definition to determine whether it's included by default in the objects returned from a find call. Set it to false for fields you want to suppress by default.

T = db.model('T', new Schema({ x: { type: String, select: false }}));
T.find(..); // field x will not be included..
// .. unless overridden;
T.find().select('+x').exec(callback);

you can use .populate() -- the 2nd argument will take a -fieldname, assuming your item.created_by is a schema reference to a User object...

Item.findById(id).populate('created_by', '-salt -password_hash').exec(function(err, item){
 //item.created_by will have user object
 //without salt or password_hash fields.
});

Another approach is a set of trimmer/cleaner functions that your application calls prior to sending the object.

server.get("/api/user/:userId", function(req, res, next){
    var id = req.params.userId;
    User.findById(id, function(err, doc){
        if(err){
            return next(err);
        }
        sendUtils.sendUser(req, res, doc);
    });
});


sendUtils.sendUser = function(req, res, doc){
    res.send(_.omit(doc, ['__id', 'hiddenfield', 'hiddenfield2']);
}

(Uses underscore.js omit function.)