Repository pattern in conjunction with Mongoose ODM
This article will discuss the implementation of the Repository pattern in conjunction with the Mongoose ODM for use in Node.js projects. Mongoose ODM tools provide a very convenient wrapper for implementing requests to MongoDB using a style similar to LINQ. Below is the implementation of the repository on the example of the UserRepo module for the User model.
Implementation description
When creating an instance of UserRepo, the mongoose object that was initialized is passed to the constructor as a dependency.
Next, using mongoose.model ('User'); the object is mapped to the base and stored in a property called UserModel. This property is used in a number of methods to gain access to the functions of the model, which will allow forming a Query object for further use. Among these methods in the implementation, you can select Select and SelectOne. When calling these methods, the client receives a Query object and, remarkably, at this moment the query to the database is not performed. This fact allows you to create a request in portions and execute it at the right time.
In the IsExistsLogin method, you can see a visual application of the call to the SelectOne () method and the subsequent generation and execution of a query.
')
Basic implementation example
function UserRepo ( mongoose ) {
var that = this ;
that. UserModel = mongoose. model ( 'User' ) ;
that. IsExistsLogin = function ( login , cb ) {
that. SelectOne ( ) . where ( 'login' , login ) . run ( function ( err , user ) {
cb ( err , user ) ;
} ) ;
} ;
that. Save = function ( user , cb ) {
user. save ( function ( err ) {
cb ( err ) ;
} ) ;
} ;
that. Delete = function ( user , cb ) {
user. remove ( function ( err ) {
cb ( err ) ;
} ) ;
} ;
that. Select = function ( ) {
return that. UserModel . find ( { } ) ;
} ;
that. SelectOne = function ( ) {
return that. UserModel . findOne ( { } ) ;
} ;
}
exports. UserRepo = UserRepo ;
For example, in the implementation of the data access model, you can call the IsExistsLogin method of the repository in this way:
userRepo. IsExistsLogin ( reqBody. UserName , function ( err , user ) {
if ( user ) {
user. email = reqBody. userMail ;
user. password = reqBody. userPasswd ;
}
next ( err , user ) ;
} ) ;
Conclusion
This basic implementation of the repository can later be supplemented by various methods to meet the needs of a particular client.