osr
Version:
osr
85 lines (78 loc) • 2.67 kB
JavaScript
var Mongoose = require("mongoose");
var Schema = require("../schema");
var Model = require("../model");
var Mongo = function(options){
this.uri = options.uri;
this.options = options;
this.schemas = {};
this.models = {};
this.collections = {};
if(!this.uri){
this.conn = Mongoose.createConnection()
}else{
this.conn = Mongoose.createConnection(this.uri);
}
}
Mongo.prototype.define = function(name,model,rename){
this.schemas[name] = new Schema(model.schema);
this.collections[name] = this.conn.model(name,new Mongoose.Schema(model.schema.schema),rename||name);
this.models[name] = model;
return this.models[name];
}
Mongo.prototype.findOne = function(){
var db = this.collections[this.name];
if(db){
return db.findOne.apply(db,arguments);
}else{
if(typeof(arguments[arguments.length-1]) == "function"){
arguments[arguments.length-1](new Error("MONGODB:The "+this.name+" COLLECTION NOT FOUND"));
}
}
}
Mongo.prototype.find = function(){
var db = this.collections[this.name];
if(db){
return db.find.apply(db,arguments);
}else{
if(typeof(arguments[arguments.length-1]) == "function"){
arguments[arguments.length-1](new Error("MONGODB:The "+this.name+" COLLECTION NOT FOUND"));
}
}
}
Mongo.prototype.update = function(){
var db = this.collections[this.name];
if(db){
return db.update.apply(db,arguments);
}else{
if(typeof(arguments[arguments.length-1]) == "function"){
arguments[arguments.length-1](new Error("MONGODB:The "+this.name+" COLLECTION NOT FOUND"));
}
}
}
Mongo.prototype.create = function(obj,cb){
var db = this.collections[this.name];
var schema = this.schemas[this.name];
if(db){
var oNew = new db();
for(var key in schema.schema.schema){
oNew[key] = obj[key];
}
return oNew.save(cb);
}else{
if(typeof(arguments[arguments.length-1]) == "function"){
arguments[arguments.length-1](new Error("MONGODB:The "+this.name+" COLLECTION NOT FOUND"));
}
}
}
Mongo.prototype.del = function(condition,cb){
var db = this.collections[this.name];
var schema = this.schemas[this.name];
if(db){
return db.remove(condition,cb);
}else{
if(typeof(arguments[arguments.length-1]) == "function"){
arguments[arguments.length-1](new Error("MONGODB:The "+ this.name+" COLLECTION NOT FOUND"));
}
}
}
module.exports = exports = Mongo;