📜 ⬆️ ⬇️

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



')
Basic implementation example


  1. function UserRepo ( mongoose ) {
  2. var that = this ;
  3. that. UserModel = mongoose. model ( 'User' ) ;
  4. that. IsExistsLogin = function ( login , cb ) {
  5. that. SelectOne ( ) . where ( 'login' , login ) . run ( function ( err , user ) {
  6. cb ( err , user ) ;
  7. } ) ;
  8. } ;
  9. that. Save = function ( user , cb ) {
  10. user. save ( function ( err ) {
  11. cb ( err ) ;
  12. } ) ;
  13. } ;
  14. that. Delete = function ( user , cb ) {
  15. user. remove ( function ( err ) {
  16. cb ( err ) ;
  17. } ) ;
  18. } ;
  19. that. Select = function ( ) {
  20. return that. UserModel . find ( { } ) ;
  21. } ;
  22. that. SelectOne = function ( ) {
  23. return that. UserModel . findOne ( { } ) ;
  24. } ;
  25. }
  26. 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:

  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 implementation of the repository can later be supplemented by various methods to meet the needs of a particular client.

Source: https://habr.com/ru/post/139719/


All Articles