Skip to content

Instantly share code, notes, and snippets.

@iraklisg
Forked from SerhiiKozachenko/repository.js
Created August 10, 2017 09:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save iraklisg/01173674b5b4702ca91fb1be33021623 to your computer and use it in GitHub Desktop.
Save iraklisg/01173674b5b4702ca91fb1be33021623 to your computer and use it in GitHub Desktop.
Mongoose odm and repository pattern.
var mongoose = require('mongoose');
var repository = function (modelName) {
var self = this;
self.Model = require('../models/' + modelName);
self.FindById = function (id, cb) {
self.FindOne({
_id : id
}, function(err, entity) {
cb(err, entity);
});
};
self.FindOne = function (params, cb) {
self.Model.findOne(params, function (err, entity) {
if (!err && !entity) {
err = true;
}
cb(err, entity);
});
};
self.FindAll = function (params, cb, lean) {
if (!lean) {
self.Model.find(params).exec(cb);
} else {
self.Model.find(params).lean().exec(cb);
}
};
self.Save = function (obj, cb) {
var entity = new self.Model(obj);
entity.save(function (err) {
cb(err);
});
};
self.Update = function (entity, cb) {
self.FindById(entity.id, function (err, oldEntity) {
if (err) {
cb(err);
} else {
oldEntity = entity;
oldEntity.save(cb);
}
})
};
self.Delete = function (entity, cb) {
entity.remove(function (err) {
cb(err);
});
};
};
repository.GetModel = function (modelName) {
return mongoose.model(modelName);
};
module.exports.Repository = repository;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment