Repository pattern in conjunction with Mongoose ODM

    This article will discuss the implementation of the Repository pattern in conjunction with Mongoose ODM for use in Node.js projects.
    Mongoose ODM Tools - Provides a very convenient wrapper for querying MongoDB through a style similar to LINQ. Below is a repository implementation using the UserRepo module for the User model as an example.


    Description of implementation


    • When creating an instance of UserRepo, the mongoose object that was initialized earlier is passed to the constructor as a dependency
    • Next, use mongoose.model ('User'); the model 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 model functions that will allow you to create a Query object for future use. Among these methods in the implementation, we can distinguish Select and SelectOne. When these methods are called, the client receives an object of type Query and, what is remarkable, at this moment a query to the database is not made. This fact allows you to form a request in batches 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 the request.


    Basic implementation example


    1. function UserRepo (mongoose) {    
    2.     var that = this;
    3.     that.UserModel = mongoose.model ('User');
    4.  
    5.     that.IsExistsLogin = function (login, cb) {
    6.         that.SelectOne (). where ('login', login) .run (function (err, user) {            
    7.             cb (err, user);
    8.         });
    9.     };
    10.  
    11.     that.Save = function (user, cb) {        
    12.         user.save (function (err) {
    13.            cb (err);
    14.         });
    15.     };
    16.  
    17.     that.Delete = function (user, cb) {
    18.         user.remove (function (err) {
    19.             cb (err);
    20.         });
    21.     };
    22.  
    23.     that.Select = function () {
    24.         return that.UserModel.find ({});
    25.     };
    26.  
    27.     that.SelectOne = function () {
    28.         return that.UserModel.findOne ({});
    29.     };
    30. }
    31.  
    32.  
    33. exports.UserRepo = UserRepo;


    For example, in the implementation of the data access model, you can call the repository's IsExistsLogin method in this way:

    1. userRepo.IsExistsLogin (reqBody.userName, function (err, user) {
    2.         if (user) {
    3.            user.email = reqBody.userMail;
    4.            user.password = reqBody.userPasswd;
    5.         }
    6.         next (err, user);
    7. });


    Conclusion

    This basic repository implementation can be further supplemented by various methods to meet the needs of a particular client.

    Also popular now: