Skip to content

Instantly share code, notes, and snippets.

@smooJitter
Forked from SerhiiKozachenko/repository.js
Created January 3, 2017 20:58
Show Gist options
  • Save smooJitter/6233d2b027e30ec4d1ca54b2b6ab2d54 to your computer and use it in GitHub Desktop.
Save smooJitter/6233d2b027e30ec4d1ca54b2b6ab2d54 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