A Mongoose Repository Class
Make sure you're using Nodejs 8.x or higher, for async/await
to work
If you're working on Nodejs 6.x, please install morepo version 0.8
You can install this module with NPM:
npm install --save morepo
You can use this class like it is or make a specific Repository class that extends this class
const mongoose = require('mongoose');
const Repository = require('morepo');
const postRepo = new Repository(mongoose.model('Post'));
const mongoose = require('mongoose');
const Repository = require('morepo');
class PostRepository extends Repository {
constructor(model) {
super(model || mongoose.model('Post'));
}
// Override an existing function to add some custom functionality
async findByObjectId(objectId) {
try {
if (!objectId) {
return {error: 'No ObjectId given'};
}
const body = await this.find(
{_id: objectId},
this.generateOptions({multiple: false})
);
if (body === null) {
return {error: 'No posts found'};
}
return body;
} catch (error) {
return {error: error.message};
}
}
generateOptions(options) {
const base = {
populate: [
{path: 'author', select: '-password -registration_date -__v'},
{path: 'comments'}
],
sort: {date_created: 'descending'},
multiple: true
};
return super.generateOptions(base, options);
}
}
const postRepo = new PostRepository(mongoose.model('Post'));
Creates a new instance of the Repository
- model - Mongoose Model
- Options:
- applyStatics - default: true Applies all static model functions to the Repo
New instance of the Repository
- obj - Object to save to the database
Given object saved to the database
Executes the given query
- query - Object
- Options:
- select
- populate
- If something else than an Array, String or Object is given, the value is skipped
- Examples
Populate examples:
String:
created_by
Object (with multilevel populate):{ path: 'friends', // Get friends of friends - populate the 'friends' array for every friend populate: { path: 'friends' } }
[One of the 2 above]
- limit
- skip
- sort
- lean - default: false
- count - default: false
- multiple - default: true
Query result
If multiple
is true
: it'll return an Array
, else it'll return an Object
Looks for 1 document based on the objectId
- query - Object
- Options:
- select
- populate
- lean - default: false
The request document
Retrieves all documents in that collection
none
Array with all documents in that collection
Retrieves a document by it's ID, assigns the new values to it (thanks you lodash) and saves it
- objectId - Object || String
- newValues - Object
The updated document
Removes the document identified by the given ObjectID from the collection
- objectId - Object || String
The remove's result
v1.0.0
- Tests
- Folder with examples
- Better Doc and readme