Create MongoDB Backend object
494866
function BackendStorage (gateway, opts){
    
    // prepare ourself to make debug possible
    this.debug  =opts.debug;
    this.gateway=gateway;

    this.opts=
       { hostname : opts.mongodb.hostname || "localhost"
       , username : opts.mongodb.username
       , password : opts.mongodb.password
       , basename : opts.mongodb.basename || opts.mongo.username
       , port     : opts.mongodb.port     || 27017
    };
    this.uid ="mongodb://" + this.opts.username + ':' + this.opts.password + "@" + this.opts.hostname +':'+ this.opts.port  + "/" + this.opts.basename;
    
    // create initial connection handler to database
    CreateConnection (this);  
}
1286783
def parse_backend(backend):
    """"""
    r = urlparse.urlsplit(backend)
    scheme, host = r.scheme, r.netloc
    path, query = r.path, r.query
    if path and not query:
        query, path = path, ''
        if query:
            if query.find('?'):
                path = query
            else:
                query = query[1:]
    if query:
        params = dict(urlparse.parse_qsl(query))
    else:
        params = {}

    return scheme, host, params
620361
def set_backend(self, backend):
        """"""
        if isinstance(backend, str):
            name = backend
            args = []
            kwargs = {}
        elif isinstance(backend, (tuple, list)):
            name = ''
            args = []
            kwargs = {}
            for i in range(len(backend)):
                if i == 0:
                    name = backend[i]
                else:
                    if isinstance(backend[i], dict):
                        kwargs.update(backend[i])
                    else:
                        args += backend[i]
        else:
            raise TypeError("Backend must be string, tuple, or list")
        if name in available_backends:
            self.backend = name
            self._backend = available_backends[name]()
        elif name is None:
            # The base class should not be called.
            raise Exception(("A backend (e.g. 'jNeuroML' or 'NEURON') "
                             "must be selected"))
        else:
            raise Exception("Backend %s not found in backends.py"
                            % name)
        self._backend.model = self
        self._backend.init_backend(*args, **kwargs)
121527
def factory_object(self, index, doc_type, data=None, id=None):
        
        data = data or {}
        obj = self.model()
        obj._meta.index = index
        obj._meta.type = doc_type
        obj._meta.connection = self
        if id:
            obj._meta.id = id
        if data:
            obj.update(data)
        return obj
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();
      }
    });
  });
}
21680
function setupDbHelper( user_options ) {
  var options = user_options || {}

  /**
   * @returns {Promise<MongooseThenable>}
   */
  function setupDb() {
    return connection( options.connection )
      .then(
        /**
         * @param {Object} db
         * @param {Function} db.model
         *
         * @throws {Error}
         * @returns {*}
         */
        function ( db ) {
          try {
            if ( Array.isArray( options.schemas ) ) {
              options.schemas.forEach(
                function ( schema ) {
                  var keys = Object.keys( schema );

                  db.model( keys[ 0 ], schema[ keys[ 0 ] ] );
                }
              );
            }

            return db;
          } catch ( err ) {
            throw err;
          }
        }
      )
      .catch(
        function ( err ) {
          throw err
        }
      )
  }

  return setupDb
}
319152
function generateAdminRouter(conf) {
  var awsKey = conf.aws.key;
  var awsSecret = conf.aws.secret;

  var api = apiFactory(log);
  var p = q.defer();

  // Register backup handlers:

  backup.registerHandler('s3', backupHandlers.genS3BackupHandler(
        awsKey,
        awsSecret
  ));

  MongoClient.connect(conf.database.url, function(err, db) {
    if(err) {
      p.reject(err);
      return;
    }

    var backupCollection = db.collection(BACKUP_COLLECTION_NAME);
    var liveBackups = {};

    //Lists all persisted backups
    api.register('backup', 'list', 'GET', function() {
        var results = backupCollection.find({});
        return q.nbind(results.toArray, results)();
    });

    api.register('backup', 'stat', 'GET', [ 'id' ], function(id) {
      if(liveBackups[id]) {
        return q(liveBackups[id]);
      }

      return q.nbind(backupCollection.findOne, backupCollection)({ backupId: id })
        .then(function(r) {
          if(!r) {
            return q({ 'error': true, msg: 'backup with id ' + id + ' not found'});
          }

          return q({ 'status': 'saved' });
        });
    });

    //Request object must be of the form
    //  {
    //    collections: [<String>],
    //    type: <String>,
    //    opts: <Object>
    //  }
    api.register('backup', 'start', 'POST', function(args) {
      var id = uuid.v1();
      // TODO: add a call to mongo's admin.serverStatus function to get the time on server.
      var backupTimestamp = new Date();
      liveBackups[id] = { 'status': 'in-progress' };
      backup.create(conf.backups.target, args.collections, args.type, args.opts)
        .then(function(backupRecord) {
          backupRecord.name = args.name;
          backupRecord.timestamp = backupTimestamp.toISOString();
          backupRecord.backupId = id;
          backupCollection.insert(backupRecord, function(e) {
            if(e) {
              liveBackups[id] = { 'status': 'failed' };
              log.error(e);
            }
            delete liveBackups[id];
          });
        })
        .then(null, log.error.bind(log));
      return q({id: id});
    });


    //FIXME use tickets to manage restore ops (similar to backups)

    api.register('backup', 'restore', 'POST', function(args) {
      var id = args.id;
      return q.nbind(backupCollection.findOne, backupCollection)({ backupId: id })
        .then(function(r) {
          if(!r) {
            return q({ error: true, msg: 'backup with id ' + id + ' not found ' });
          }
          return backup.restore(r, conf.backups.target);
        });
    });

    p.resolve(api.getApp());
  });

  return p.promise;
}
255183
function create(req, res, next) {
  var body = req.body
    , slug = string.slugify(body.title);

  db.tags.findBySlug(slug, function(err, tag) {
    if(err && err.statusCode != 404) { return next(err); }

    if(tag) {
      res.json(201, tag);
    } else {
      db.tags.create(req.body, function(err, tag) {
        if(err) {
          next(err);
        } else {
          res.json(201, tag);
          signals.emit('tag:create', tag);
        }
      });
    }
  });
}
772734
def createVertex(self, collectionName, docAttributes, waitForSync = False) :
        """"""
        url = "%s/vertex/%s" % (self.URL, collectionName)

        store = DOC.DocumentStore(self.database[collectionName], validators=self.database[collectionName]._fields, initDct=docAttributes)
        # self.database[collectionName].validateDct(docAttributes)
        store.validate()

        r = self.connection.session.post(url, data = json.dumps(docAttributes, default=str), params = {'waitForSync' : waitForSync})

        data = r.json()
        if r.status_code == 201 or r.status_code == 202 :
            return self.database[collectionName][data["vertex"]["_key"]]

        raise CreationError("Unable to create vertice, %s" % data["errorMessage"], data)
623113
function (options, callback) {
            MongoClient.connect(connString, function (err, db) {
                var at = db.collection(collection);
                at.findOne({
                    'appId': options.appId,
                    'appSecret': options.appSecret,
                    'expire': {'$gt': new Date()}
                }, function (err, at) {
                    db.close();
                    if(at == null){
                        callback('error');
                    } else {
                        callback(err, at.token);
                    }
                });
            });
        }
617084
def create(cls, job_id, spider, workflow, results=None,
               logs=None, status=JobStatus.PENDING):
        """"""
        obj = cls(
            job_id=job_id,
            spider=spider,
            workflow=workflow,
            results=results,
            logs=logs,
            status=status,
        )
        db.session.add(obj)
        return obj
672691
def create_mongo_db(database_name, collection_name, initial_document):
    """"""
    response_dict = {}
    try:
        mongodb_client_url = getattr(settings, 'MONGODB_CLIENT',
                                 'mongodb://localhost:27017/')
        mc = MongoClient(mongodb_client_url,document_class=OrderedDict)

        db = mc[str(database_name)]
        collection = db[str(collection_name)]

        d = json.loads(initial_document, object_pairs_hook=OrderedDict)

        collection.save(d)

    except:
        # error connecting to mongodb
        response_dict['error'] = str(sys.exc_info())

    return response_dict
1253715
def _create(self, postData) :
        """"""
        if self.infos is None :
            r = self.connection.session.post(self.indexesURL, params = {"collection" : self.collection.name}, data = json.dumps(postData, default=str))
            data = r.json()
            if (r.status_code >= 400) or data['error'] :
                raise CreationError(data['errorMessage'], data)
            self.infos = data
54721
function(req, res, fromMessage) {
            var name = req.params.name;
            var doc  = req.body;
            var id   = this.toId(req.params.id || doc._id);
            if (typeof id === 'undefined' || id === '') {
                return res.send(400, "invalid id.");
            }
            doc._id   = id;
            doc._time = new Date().getTime();
            var collection = new mongodb.Collection(this.db, name);
            collection.update(
                { "_id" : id },
                doc,
                { safe:true, upsert:true },
                function(err, n) {
                    if(err) {
                        res.send("Oops!: " + err);
                    } else {
                        if (n==0) {
                            res.send(404, 'Document not found!');
                        } else {
                            var msg = {
                                method: 'update',
                                id: doc._id,
                                time: doc._time,
                                data: doc
                            };
                            rest.onSuccess(name, msg, fromMessage);
                            res.send(doc);
                        }
                    }
                }
            );
        }
1235512
function create (key, scopes, callback) {
    const data = {
      key: key,
      scopes: scopes
    }

    db.put(key, data, function (err) {
      if (err) return callback(err)
      else callback(null, data)
    })
  }
639392
def _apply_groups_to_backend(cls, obj, options, backend, clone):
        ""
        obj_handle = obj
        if options is None:
            if clone:
                obj_handle = obj.map(lambda x: x.clone(id=None))
            else:
                obj.map(lambda x: setattr(x, 'id', None))
        elif clone:
            obj_handle = obj.map(lambda x: x.clone(id=x.id))

        return StoreOptions.set_options(obj_handle, options, backend=backend)
448542
def load_object(s):
    
    try:
        m_path, o_name = s.rsplit('.', 1)
    except ValueError:
        raise ImportError('Cant import backend from path: {}'.format(s))

    module = import_module(m_path)
    return getattr(module, o_name)