Created
September 16, 2016 01:44
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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