This allows one to create a model instance.

@param {string} connectionName
@param {string} collectionName
@param {Object} obj
@param {Function} cb
@returns {Object} Model Instance
166515
function (connectionName, collectionName, obj, cb) {
        if (_.isObject(obj)) {
            try {
                var modelInstance = new this._model(obj);
                return cb(null, modelInstance);
            }
            catch (err) {
                return cb(err, null);
            }
        }
    }
1218571
function (callback) {
                var self = this;

                var deferred = Q.defer();
                callback = Qext.makeNodeResolver(deferred, callback);

                var breakExec = {};
                Async.waterfall([
                    function (next) {
                        if (!self.collectionName) {
                            next({
                                name: 'InternalError',
                                err: "collectionName property is not set for model " + self.identity
                            });
                        } else {
                            var dbName = self.dbName || Shared.config("environment.defaultMongoDatabase");
                            var db = self.db(dbName);
                            if (db) {
                                next(null, db);
                            }
                            else {
                                next({
                                    name: 'InternalError',
                                    err: "No connection to database " + self.identity
                                });
                            }
                        }
                    },
                    function (db, next) {

                        if (!db || _.isEmpty(db)) {
                            Logger.error("No db connection");
                            next("No db connection");
                        }
                        else {
                            //try to get exiting collection
                            db.collection(self.collectionName, {strict: true}, function (err, collection) {
                                if (!err) {
                                    //collection exists already
                                    self._collection = collection;
                                    //do not apply indexes to exiting collection, since this operation is time consuming
                                    next(breakExec, collection);
                                }
                                else {
                                    var collectionOptions = self.collectionOptions || {};
                                    db.createCollection(self.collectionName, collectionOptions, function (err, collection) {
                                        if (!err) {
                                            next(null, collection);
                                        }
                                        else {
                                            db.collection(self.collectionName, {strict: true}, function (err, collection) {
                                                if (!err) {
                                                    //collection exists already
                                                    self._collection = collection;
                                                    //do not apply indexes to exiting collection, since this operation is time consuming
                                                    next(breakExec, collection);
                                                }
                                                else {
                                                    Logger.error(err);
                                                    next(err);
                                                }
                                            });
                                        }
                                    });
                                }
                            });
                        }
                    },
                    function (collection, next) {
                        //store new collection
                        self._collection = collection;

                        if (_skipDatabaseIndexingOnNewCollections()) {
                            return next(null, collection);
                        }

                        //apply all indexes on collection
                        self.ensureAllIndexes(function (err) {
                            next(err, collection);
                        });
                    },
                    function (collection, next) {
                        //return collection
                        next(null, collection);
                    }
                ], function (err, collection) {
                    if (!err || err === breakExec) {
                        callback(null, collection);
                    }
                    else {
                        callback(err);
                    }
                });

                return deferred.promise;
            }
218423
function Connection(conn) {
	if(!(this instanceof Connection)) {
		return new Connection(conn);
	}
	var self = this;
	if(!conn) { throw new TypeError("no connection set"); }
	self._connection = conn;
}
894601
function (DB_name, name, onDone, prefix) {

	//LOG.warn('init ' + DB_name + ' collection: ' + name, 'SR.DB');

	if (l_DBclient.hasOwnProperty(DB_name) === false) {
		LOG.error('DBclient not init or authenticated for DB [' + DB_name + ']', 'SR.DB');
		return UTIL.safeCall(onDone, false);
	}

	// check if already init
	if (l_getCollection(name, undefined, DB_name) !== undefined) {
		LOG.warn('DB [' + DB_name + '] collection [' + name + '] already loaded', 'SR.DB');
		LOG.warn('please check if different codes are using the same collection names', 'SR.DB');
		// NOTE: we assume double declaration of collection name is ok
		return UTIL.safeCall(onDone, true);
	}

	// build collection name to prefix with server name or a specified prefix
	var collection_name = (prefix || SR.Settings.SERVER_INFO.name) + ':' + name;

	// original simple version
	//var collection_name = name;

	l_DBclient[DB_name].collection(collection_name,
		function (err, collection) {
			if (err) {
				LOG.error(err, 'SR.DB');
				LOG.error('init DB [' + DB_name + ' ] collection [' + collection_name + '] error', 'SR.DB');
				UTIL.safeCall(onDone, false);
			} else {
				// store each name as a collection entry in collection object
				// collection name, instance(conn) , cache (idx by _id)
				var msg = 'init DB [' + DB_name + '] collection [' + collection_name + '] success';
				LOG.debug(msg, 'SR.DB');
				if (l_clts.hasOwnProperty(DB_name) === false) {
					l_clts[DB_name] = {};
				}

				// store collection instance into a two-level map
				l_clts[DB_name][name] = collection;

				// attach entity list to collection (for object caching)
				l_clts[DB_name][name].cache = {};

				UTIL.safeCall(onDone, true);
			}
		}
	);
}
1325618
function connectToDB(connObject, ssl, _callback) {
        let connection;
        let sslObject;
        let connectionObject;
        if (ssl == true) {
            sslObject = {
                ca: fs.readFileSync(connObject.certificatePath),
            };
        }
        console.log('Setting connection params');
        if (connObject.dbtype === 'mysql') {
            if (ssl == true) {
                connectionObject = {
                    host: connObject.server,
                    port: connObject.port,
                    user: connObject.username,
                    password: connObject.password,
                    database: connObject.database,
                    connectTimeout: connObject.connTimeout,
                    ssl: sslObject,
                };
            } else {
                connectionObject = {
                    host: connObject.server,
                    port: connObject.port,
                    user: connObject.username,
                    password: connObject.password,
                    database: connObject.database,
                    connectTimeout: connObject.timeout,
                };
            }

            console.log('After initializing params for connection');
            // check if db connection string is provided
            if (checkTypes.assigned(connObject.connectionString)) {
                connection = mysql.createConnection(connectString);
            } else {
                connection = mysql.createConnection(connectionObject);
            }
            console.log('Calling connection connect');
            connection.connect(function(err) {
                _callback(err, connection);
                return connection;
            });
            return connection;
        } else {
            // TBD: Add implementation for handling other types of database and drivers.
            console.log('Invalid Database Type');
            return 0;
        }
    }
1247298
private void populateCollectionFromMap(Object entity, PersistenceDelegator delegator, Relation relation,
            Object relObject, Map<String, Object> relationsMap)
    {
        EntityMetadata childMetadata = KunderaMetadataManager.getEntityMetadata(delegator.getKunderaMetadata(),
                relation.getTargetEntity());
        // Map collection to be set into entity
        Map<Object, Object> relationshipEntityMap = new HashMap<Object, Object>();

        if ((relObject == null || ProxyHelper.isProxyCollection(relObject)) && relationsMap != null
                && !relationsMap.isEmpty())
        {
            for (String relationName : relationsMap.keySet())
            {
                Object relationValue = relationsMap.get(relationName);
                if (relationValue instanceof Map)
                {
                    Map<Object, Object> relationValueMap = (Map<Object, Object>) relationValue;

                    // Client for target entity
                    Client targetEntityClient = delegator.getClient(childMetadata);

                    for (Object targetEntityKey : relationValueMap.keySet())
                    {
                        // Find target entity from database
                        Object targetEntity = targetEntityClient.find(childMetadata.getEntityClazz(), targetEntityKey);
                        if (targetEntity != null && targetEntity instanceof EnhanceEntity)
                        {
                            targetEntity = ((EnhanceEntity) targetEntity).getEntity();
                        }

                        // Set source and target entities into Map key entity
                        Object mapKeyEntity = relationValueMap.get(targetEntityKey);
                        Class<?> relationshipClass = relation.getMapKeyJoinClass();
                        for (Field f : relationshipClass.getDeclaredFields())
                        {
                            if (f.getType().equals(entity.getClass()))
                            {
                                PropertyAccessorHelper.set(mapKeyEntity, f, entity);
                            }
                            else if (f.getType().equals(childMetadata.getEntityClazz()))
                            {
                                PropertyAccessorHelper.set(mapKeyEntity, f, targetEntity);
                            }
                        }

                        // Finally, put map key and value into collection
                        relationshipEntityMap.put(mapKeyEntity, targetEntity);
                    }
                }
            }
            relObject = relationshipEntityMap;
        }

        // Set relationship collection into original entity
        PropertyAccessorHelper.set(entity, relation.getProperty(), relObject);

        // Add target entities into persistence cache
        if (relObject != null && !ProxyHelper.isProxyCollection(relObject))
        {
            for (Object child : ((Map) relObject).values())
            {
                if (child != null)
                {
                    Object childId = PropertyAccessorHelper.getId(child, childMetadata);
                    PersistenceCacheManager.addEntityToPersistenceCache(child, delegator, childId);
                }
            }
        }
    }
913644
public MongoCollection<Document> getCollection(String dbName, String collectionName) {
		return getDb(dbName).getCollection(collectionName);
	}
303415
function create(body, cb) {
  var validates = Schema(body);

  if(!validates) {
    return cb(new exceptions.BadRequest());
  }

  body.slug = string.slugify(body.title);

  var q = qb.insert(body);
  db.getClient(function(err, client, done) {
    client.query(q[0], q[1], function(err, r) {
      if(err) {
        if(err.code == 23505) {
          err = new exceptions.AlreadyExists();
        }
        cb(err);
        done(err);
      } else {
        cb(null, r.rows[0]);
        done();
      }
    });
  });
}
689757
function (cb) {

                var db  = linz.mongoose.connection.db;

                db.collection(linz.get('configs collection name'), function (err, collection) {
                    return cb(err, collection);
                });

            }
1171892
function initServiceModel(connectionUrl) {
  log.logger.debug("initServiceModel ", {connectionUrl: connectionUrl});
  if (!connectionUrl) {
    log.logger.error("No Connection Url Specified");
    return null;
  }

  //If the connection has not already been created, create it and initialise the Service Schema For That Domain
  if (!domainMongooseConnections[connectionUrl]) {
    log.logger.debug("No Connection Exists for " + connectionUrl + ", creating a new one");
    domainMongooseConnections[connectionUrl] = mongoose.createConnection(connectionUrl);
    domainMongooseConnections[connectionUrl].model(SERVICE_MODEL, ServiceSchema);

    //Setting Up Event Listeners
    domainMongooseConnections[connectionUrl].on('connecting', function(msg){
      log.logger.debug("Mongoose Connecting", {msg: msg, connectionUrl: connectionUrl});
    });

    domainMongooseConnections[connectionUrl].on('error', function(msg){
      log.logger.error("Mongoose Connection Error", {msg: msg, connectionUrl: connectionUrl});
    });

    domainMongooseConnections[connectionUrl].on('connected', function(msg){
      log.logger.debug("Mongoose Connected", {msg: msg, connectionUrl: connectionUrl});
    });
  } else {
    log.logger.debug("Connection Already Exists.");
  }

  return domainMongooseConnections[connectionUrl];
}
1271251
function getFormApps(connections, options, cb) {
  var validate = validation(options);
  function validateParams(cb) {
    validate.has("formId",cb);
  }
  validateParams(function(err) {
    if (err) {
      return cb(err);
    }
    var conn = connections.mongooseConnection;
    var appFormsModel = models.get(conn, models.MODELNAMES.APP_FORMS);
    var formId = options.formId;
    var restrictToUser = options.restrictToUser;

    groups.validateFormAllowedForUser(connections, restrictToUser, formId, function(err) {
      if (err) {
        return cb(err);
      }

      groups.getAppsForUser(connections, restrictToUser, function(err, allowedApps) {
        var query = {forms: formId};
        if (allowedApps) {
          query.apps = {$in: allowedApps};
        }
        appFormsModel.find(query).exec(function(err, apps) {
          if (err) {
            return cb(err);
          }
          return cb(null, apps);
        });
      });

    });
  });
}
26818
function(dbName, collection, metric, callback) {
	var colInfo = {capped:true, size:options.size*options.max, max:options.max};

	database(dbName, function(err, db) {
		if (err) {
			db.close();
			return callback(err);
		};

		db.createCollection(collection, colInfo, function(err, collClient) {      
			collClient.insert(metric, function(err, data){
				if (err) callback(err);
				if (!err) callback(false, collection);
			});
		});
	});
}
651596
function Connection(conn) {
	if(!(this instanceof Connection)) {
		return new Connection(conn);
	}
	var self = this;
	if(!conn) { throw new TypeError("no connection set"); }
	self._connection = conn;
	self._connect    = Q.nfbind(self._connection.connect.bind(self._connection));
	self._query      = Q.nfbind(self._connection.query.bind(self._connection));

	// These do not have callbacks when PoolConnection is used
	//self._end        = Q.nfbind(self._connection.end.bind(self._connection));
	//self._release        = Q.nfbind(self._connection.release.bind(self._connection));

	self._changeUser = Q.nfbind(self._connection.changeUser.bind(self._connection));
	db.Connection.call(self, conn);
}
705807
function loadObject(data, db, callback) {
    callback = callback || function() {};
    var iterator = function(modelName, next){
        insertCollection(modelName, data[modelName], db, next);
    };
    async.forEachSeries(Object.keys(data), iterator, callback);
}
1111668
function MongoStore(options, callback) {
    options = options || {};
    Store.call(this, options);

    if(options.url) {
      var db_url = url.parse(options.url);

      if (db_url.port) {
        options.port = parseInt(db_url.port);
      }
      
      if (db_url.pathname != undefined) {
        var pathname = db_url.pathname.split('/');

        if (pathname.length >= 2 && pathname[1]) {
          options.db = pathname[1];
        }
        
        if (pathname.length >= 3 && pathname[2]) {
          options.collection = pathname[2];
        }
      }
      
      if (db_url.hostname != undefined) {
        options.host = db_url.hostname;
      }

      if (db_url.auth != undefined) {
        var auth = db_url.auth.split(':');

        if (auth.length >= 1) {
          options.username = auth[0];
        }
        
        if (auth.length >= 2) {
          options.password = auth[1];
        }
      }
    }
  
    if (options.mongoose_connection){
      if (options.mongoose_connection.user && options.mongoose_connection.pass) {
        options.username = options.mongoose_connection.user;
        options.password = options.mongoose_connection.pass;
      }

      this.db = new mongo.Db(options.mongoose_connection.db.databaseName, {});

    } else {
      if(!options.db) {
        throw new Error('Required MongoStore option `db` missing');
      }

      if (typeof options.db == "object") {
        this.db = options.db; // Assume it's an instantiated DB Object
      }
      else {
        this.db = new mongo.Db(options.db, {});
      }
    }
    this.db_collection_name = options.collection || defaultOptions.collection;

    if (options.hasOwnProperty('stringify') ?
        options.stringify : defaultOptions.stringify) {
      this._serialize_session = JSON.stringify;
      this._unserialize_session = JSON.parse;
    } else {
      // Copy each property of the session to a new object
      this._serialize_session = function(session) {
        var obj = {};
        for (var prop in session) {
          if (prop === 'cookie') {
            // Convert the cookie instance to an object, if possible
            // This gets rid of the duplicate object under session.cookie.data property
            obj.cookie = session.cookie.toJSON ? session.cookie.toJSON() : session.cookie;
          } else {
            obj[prop] = session[prop];
          }
        }

        return obj;
      };

      this._unserialize_session = function(x) { return x; };
    }
    
    var self = this;
    this._get_collection = function(callback) {
      if (self.collection) {
        callback && callback(self.collection);
      } else {
        self.db.collection(self.db_collection_name, function(err, collection) {
          if (err) {
            throw new Error('Error getting collection: ' + self.db_collection_name  + ' <' + err + '>');
          } else {
            self.collection = collection;

            // Make sure we have a TTL index on "expires", so mongod will automatically
            // remove expired sessions. expireAfterSeconds is set to 0 because we want 
            // mongo to remove anything expired without any additional delay.
            self.collection.ensureIndex({expires: 1}, {expireAfterSeconds: 0}, function(err, result) {
              if (err) {
                throw new Error('Error setting TTL index on collection : ' + self.db_collection_name + ' <' + err + '>');
              }
              
              callback && callback(self.collection);
            });
            
          }      
        });    
      }
    };
    if (this.db.openCalled) {
      this._get_collection(callback)
    }
    else {
      this.db.open(function(err, db) {
        if (err) {
          throw new Error('Error connecting to database <' + err + '>');
        }

        if (options.username && options.password) {
          db.authenticate(options.username, options.password, function () {
            self._get_collection(callback);
          });
        } else {
          self._get_collection(callback);
        }
      });
    }
  }
9015
function(name, config)
{
    this.mongo    = require('mongodb');
    this.mongoose = require('mongoose');

    this.config = config;
    this.name   = name;

    this.connection = undefined;
    this.orm        = {
        instance : undefined,
        models   : {}
    };
}
1277736
function (connectionName, collectionName, relations, cb) {

      var connectionObject = connections[connectionName];
      if (!connectionObject) return cb(Errors.InvalidConnection);

      async.series(
        [
          // drop the main table
          function(cb) {

            var collection = connectionObject.collections[collectionName];
            if (!collection) return cb(Errors.CollectionNotRegistered);

            collection.dropTable(function(err) {
              // ignore "table does not exist" error
              if (err && err.code === 8704) return cb();
              if (err) return cb(err);
              cb();
            });
          },

          // drop relations
          function(cb) {
            // do it in parallel
            async.eachSeries(relations,
              function(item, cb) {

                var collection = connectionObject.collections[item];
                if (!collection) return cb(Errors.CollectionNotRegistered);

                collection.dropTable(function(err) {
                  // ignore "table does not exist" error
                  if (err && err.code === 8704) return cb();
                  if (err) return cb(err);
                  cb();
                });
              },
              function(err, results) {
                if (err) return cb(err);
                cb();
              }
            );
          }
        ],
        function(err, results) {
          if (err) return cb(err);
          cb();
        }
      );
    }