mongoose-named-scopes
🍀 Define chainable, semantic and composable Mongoose queries
// Definition (placed in Scheme)ProductSchemascope'available';ProductSchemascope'mostRecent' { return this;}; // Usage (called from anywhere)Product;User;Task;
Usage
Install it with npm:
npm install --save mongoose-named-scopes
First, you need to register the plugin into the schemas that you want to use it:
var namedScopesPlugin = ; // For one SchemaUserSchema; // For all Schemas at oncemongoose;
Then, use schema.scope
(or schema.namedScope
) to define your scopes:
// You can define scopes by chaining operator callsUserSchemascope'male'; // Or you can pass a function, for when you want to have arguments// or need to use other statementsUserSchemascope'olderThan' { // Be sure to return `this`! return this;}; UserSchemascope'youngerThan' { return this;}; // Scopes can make use of other scopes!UserSchemascope'twenties'; // Heads up! We need to implement this as a function so that the// date parameter gets evaluated when you actually call the scopeUserSchemascope'active' { const yesterday = + - 24*60*60*1000; return this;};
Now, use the named scopes as if they were query functions:
// You can specify more operatorsUser; // ... // Returning array resultsUser; // Returning single resultsUser;
Enjoy!
Contributing
Contributions are greatly appreciated!
This is a very new library that extends Mongoose in some unusual ways. Please report bugs in the Issues.
Feel free to develop additional features or fix bugs and send them over as Pull Requests.