json-object-editor
Version:
JOE the Json Object Editor | Platform Edition
95 lines (87 loc) • 3.13 kB
JavaScript
var mongojs = require('mongojs');
function Mongo(db){
var modulename = colorize('[mongo]','module');
var mBM = new Benchmarker();
var self = this;
var db = db || JOE.webconfig.joedb;
var database = mongojs(db);
database.on('error', function (err) {
console.log(modulename+' ERROR: '+err);
self = false;
})
database.on('connect',function(){
console.log(modulename+' connected to '+db+' in '+mBM.stop()+' secs');
self.Database=database;
setupIndexes();
});
function setupIndexes(){
var standard_indexes =[
{_id:1},
{itemtype:1},
{name:1},
{joeUpdated:-1}
];
//var schemalist =
//console.log(JOE.Schemas.schemaList);
JOE.Schemas.schemaList.map(sname=>{
standard_indexes.map(index=>{
self.Database[sname].ensureIndex(index, (err, good) => {
if (err) {
console.log(modulename+`indexERROR: ${sname}:`+err);
}
})
})
})
console.log(`${modulename} schema indexes checked`);
var history_indexes = [
{"itemid":1},
{"user._id":1},
{"collection":1}
];
history_indexes.map(index=>{
self.Database['_history'].ensureIndex(index, (err, good) => {
if (err) {
console.log(modulename+`indexERROR: _history:`+err);
}
})
})
console.log(`${modulename} historical indexes checked`);
}
this.get =function(collection,specs/*query,callback*/){
var specs = specs || {};
var callback = specs.callback;
var query = specs.query || {};
//logit(specs);
//var query = query || {};
if(query._id && !query._id.isCuid()){
query._id = mongojs.ObjectId(query._id);
}
query[JOE.webconfig.deleted] = {$in:[false,'false','False',undefined]};
database.collection(collection).find(query,callback);
};
this.save = function(data,collection,callback){
if(data._id && !data._id.isCuid()){
//console.log(data._id);
data._id = mongojs.ObjectId(data._id);
}
database = mongojs(db);
database.collection(collection).save(data,function(err,results){
if(err){console.log('save error: '+err)}
JOE.Cache.update(null,[collection]);
(callback||logit)(err,results);
});
};
this.saveHistory = function(data,callback){
var collection = '_history';
database.collection(collection).save(data,function(err,results){
(callback||logit)(err,results);
});
};
this.delete =function(data,collection,callback){
data.deleted = new Date().toISOString();
JOE.Mongo.save(data,collection,callback);
};
this.Database=database;
return this;
};
module.exports = new Mongo();