alphascript-server
Version:
CRUD operations for mongo and other functionalities to get started quickly in any CMS project
63 lines (49 loc) • 1.87 kB
JavaScript
var api = require('../../../');
var version = require('../../util/version');
var _schema;
function common() {
_schema = require('./schema')(api.options.mongoose);
}
common.prototype.add = function (schema) {
for (var key in schema) {
if (typeof _schema[key] !== 'undefined') {
console.log(key + ' in common db overwritten');
}
_schema[key] = schema[key];
}
};
common.prototype.disconnect = function (callback) {
this.connection.close(callback);
};
common.prototype.init = function () {
var connection = api.options.mongoose.createConnection(api.options.common, api.mongoOptions());
connection.on('connected', function () {
console.log('api common db connected successfully');
});
connection.on('error', function (err) {
api.error.log('api common db error:' + err);
});
connection.on('disconnected', function () {
delete connection;
console.log('api common db disconnected');
});
connection.on('open', function () {
console.log('api common db openned, setting up versioning collections');
});
this.connection = connection;
for (var key in _schema) {
var modelName = key[0].toUpperCase() + key.substring(1);
var collectionName = key + '_history';
var schema = new api.options.mongoose.Schema(_schema[key], api.schemaOptions());
schema.post('save', api.error.mongoHandler);
schema.post('update', api.error.mongoHandler);
schema.post('findOneAndUpdate', api.error.mongoHandler);
schema.post('insertMany', api.error.mongoHandler);
schema.plugin(version, { mongoose: api.options.mongoose, connection: connection, collection: collectionName });
this[modelName] = connection.model(key, schema);
this[modelName].on('index', function(err) {
if (err) return console.error('error on ' + this.modelName);
});
}
};
module.exports = exports = new common;