Skip to content

Instantly share code, notes, and snippets.

@ozzieperez
Created September 16, 2016 01:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ozzieperez/af10c8800418ef9c017f98eb99ed9c36 to your computer and use it in GitHub Desktop.
Save ozzieperez/af10c8800418ef9c017f98eb99ed9c36 to your computer and use it in GitHub Desktop.
Creates a $group object for Mongo aggregate that adds all the properties of a Model object and any other additions.
let Group = {
/*
* Description:
* Creates a $group object for Mongo aggregate that adds all the properties
* of a Model object and any other additions.
*
* Sample usage:
* MyCoolModel.aggregate({$match:{..}, {$group:Group.withModel(MyCoolModel, {count: { $sum: 1 }})} })
*
* Parameters:
* - model: the mongoose model object
* - additions: additional custom properties
*/
withModel(model, additions){
var result = {};
if(model) {
model.schema.eachPath(function (path) {
if (path === '_id') {
result[path] = "$" + path;
} else if (path && !path.startsWith('__'))
result[path] = {"$first": "$" + path};
});
}
if(additions) {
Object.getOwnPropertyNames(additions).forEach(prop => {
result[prop] = additions[prop];
});
}
return result;
}
}
export {Group};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment