How to use the mongodb.connect function in mongodb

To help you get started, we’ve selected a few mongodb examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github DefinitelyTyped / DefinitelyTyped / types / mongodb / mongodb-tests.ts View on Github external
.findOneAndUpdate({ name: to }, { $inc: { balance: amount } }, opts)
            .then(res => res.value);

        await session.commitTransaction();
        session.endSession();
        return { from: A, to: B };
    } catch (error) {
        // If an error occurred, abort the whole transaction and
        // undo any changes that might have happened
        await session.abortTransaction();
        session.endSession();
        throw error; // Rethrow so calling function sees error
    }
}

mongodb.connect(connectionString).then((client) => {
    client.startSession();
    client.withSession(session =>
        runTransactionWithRetry(updateEmployeeInfo, client, session)
    );
});

// https://docs.mongodb.com/manual/core/map-reduce/

// Declare emit function to be called inside map function
declare function emit(key: any, value: any): void;

interface ITestMapReduceSchema {
    cust_id: string;
    amount: number;
    status: string;
}
github mrvautin / openKB / data / mongodbUpgrade.js View on Github external
var Nedb = require('nedb');
var mongodb = require('mongodb');
var async = require('async');
var path = require('path');
var common = require('../routes/common');
var config = common.read_config();
var ndb;

// check for DB config
if(!config.settings.database.connection_string){
    console.log('No MongoDB configured. Please see README.md for help');
    process.exit(1);
}

// Connect to the MongoDB database
mongodb.connect(config.settings.database.connection_string, {}, function(err, mdb){
    if(err){
        console.log("Couldn't connect to the Mongo database");
        console.log(err);
        process.exit(1);
    }

    console.log('Connected to: ' + config.settings.database.connection_string);
    console.log('');

    insertKB(mdb, function(KBerr, report){
        insertUsers(mdb, function(Usererr, report){
            if(KBerr || Usererr){
                console.log('There was an error upgrading to MongoDB. Check the console output');
            }else{
                console.log('MongoDB upgrade completed successfully');
                process.exit();
github r-spacex / SpaceX-API / src / scripts / cores.js View on Github external
(async () => {
  let client;
  try {
    client = await MongoClient.connect(process.env.MONGO_URL, { useNewUrlParser: true });
  } catch (err) {
    console.log(err.stack);
    process.exit(1);
  }

  const col = client.db('spacex-api').collection('core');
  const launch = client.db('spacex-api').collection('launch');

  // Update status of each core from the subreddit core tracking page
  // Parses two tables: One for active cores, and one for the status unknown cores, may
  // add support for the inactive and lost cores at some point
  const result = await request('https://old.reddit.com/r/spacex/wiki/cores');
  const $ = cheerio.load(result);

  const active = $('div.md:nth-child(2) > table:nth-child(14) > tbody:nth-child(2)').text();
  const activeRow = active.split('\n').filter((v) => v !== '');
github bencevans / mongomate / app.js View on Github external
var app = express();

var mongo = require('mongodb')
, Db = require('mongodb').Db
, Connection = require('mongodb').Connection
, Server = require('mongodb').Server
, format = require('util').format;

//
// Open Mongo Connection if mongoClient is a URI
//

if(typeof mongoClient == 'string') {
  var mongoURI = mongoClient;
  mongoClient = 'connecting';
  mongo.connect(mongoURI, function(err, client) {
    mongoClient = client;
  });
}


//
// View Engine Setup/Helpers
//

fs.readdirSync(path.resolve(__dirname, './views/helpers')).forEach(function(file) {
  hbs.registerHelper(path.basename(file, '.js'), require(path.resolve(__dirname, './views/helpers/', file)));
});

//
// Express App Config/Setup
//
github olymp / olymp / graphql / store-mongo / session.js View on Github external
this.options = options;

            this.changeState('init');

            const newConnectionCallback = (err, db) => {
                if (err) {
                    this.connectionFailed(err);
                } else {
                    this.handleNewConnectionAsync(db);
                }
            };

            if (options.url) {
                // New native connection using url + mongoOptions
                MongoClient.connect(options.url, options.mongoOptions || {}, newConnectionCallback);
            } else if (options.mongooseConnection) {
                // Re-use existing or upcoming mongoose connection
                if (options.mongooseConnection.readyState === 1) {
                    this.handleNewConnectionAsync(options.mongooseConnection.db);
                } else {
                    options.mongooseConnection.once('open', () => this.handleNewConnectionAsync(options.mongooseConnection.db));
                }
            } else if (options.db && options.db.listCollections) {
                // Re-use existing or upcoming native connection
                if (options.db.openCalled || options.db.openCalled === undefined) { // openCalled is undefined in mongodb@2.x
                    this.handleNewConnectionAsync(options.db);
                } else {
                    options.db.open(newConnectionCallback);
                }
            } else if (options.dbPromise) {
                options.dbPromise
github r-spacex / SpaceX-API / src / scripts / roadster.js View on Github external
(async () => {
  let client;
  try {
    client = await MongoClient.connect(process.env.MONGO_URL, { useNewUrlParser: true });
    const col = client.db('spacex-api').collection('info');
    const data = await getData(orbitURL, earthDistURL, marsDistURL);
    console.log(data);

    await col.updateOne({ name: 'Elon Musk\'s Tesla Roadster' }, { $set: data });
    console.log('Updated!');
  } catch (err) {
    console.log(err.stack);
    process.exit(1);
  }

  if (client) {
    client.close();
  }
})();
github spadgett / LDPjs / db.js View on Github external
exports.init = function(env, callback) {
	require('mongodb').connect(env.mongoURL, function(err, conn) {
		if (err) {
			callback(err);
			return;
		}

		db = conn;
		exports.graphs = graphs();
		console.log("Connected to MongoDB at: "+env.mongoURL);
		ensureIndex();
		callback();
	});
};
github vkarpov15 / lean-mean-nutrition-sample / dependencies / setup.js View on Github external
exports.createDependencies = function(di) {
  var Mongoose = require('mongoose');

  var db = Mongoose.createConnection(
    'localhost',
    'leanmean',
    27017);

  var mongodb = require('mongodb');
  var conn;
  mongodb.connect("mongodb://localhost:27017/leanmean", function(error, db) {
    conn = db;
  });

  di.assemble([
    [
      {
        name : "fs",
        obj : require('fs')
      },
      {
        name : "FoodItem",
        factory : function() {
          var schema = require('../models/food_item.js').CreateFoodItemSchema();
          return db.model('nutrition', schema, 'nutrition');
        }
      },
github lsm / nodepress / core / db.js View on Github external
function connect(server, callback) {
    var type = typeof server;
    if (type  == 'string') {
        mongo.connect(server, callback);
        return;
    } else if (type == 'object' && !Array.isArray(server)) {
        var db = new mongo.Db(server.dbname, new mongo.Server(server.host, server.port, server.serverOptions), server.dbOptions);
        db.open(callback);
        return;
    }
    throw new Error('Server configuration not correct.');
}
github kartikayg / StatusPage / incidents-service / src / lib / db / mongo.js View on Github external
return new Promise((resolve, reject) => {
    MongoClient.connect(endpoint, DB_PARAMS, (err, db) => {
      if (err) {
        reject(err);
      }
      else {
        resolve(db);
      }
    });
  });
};