underscore.js .keys and .omit not working as expected underscore.js .keys and .omit not working as expected mongoose mongoose

underscore.js .keys and .omit not working as expected


The problem is that data passed into exec callback function is actually a Document object - which can be thought of as a collection of Models created by Mongoose. These objects have plenty of useful methods, they remember connection with db etc. - but you won't be able to process them as plain objects.

The solution is to instruct Mongoose that you actually want plain JS objects as result of the query with lean():

User.find().sort({'userName': 'ascending'}).lean().exec(function(err, data) {  // process the data});

Alternatively, you should be able to turn each model into a plain object with .toObject() method, then filter it:

var filtered = _.map(data, function(model) {  return _.omit(model.toObject(), 'password');});res.json(filtered);

... but I'd rather use the first approach. )