How to use mongodb - 10 common examples

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 montagejs / screening / server / lib / database / mongo-provider.js View on Github external
/* 
 This file contains proprietary software owned by Motorola Mobility, Inc.<br>
 No rights, expressed or implied, whatsoever to this software are provided by Motorola Mobility, Inc. hereunder.<br>
 (c) Copyright 2011 Motorola Mobility, Inc.  All Rights Reserved.
  */
var Db = require('mongodb').Db;
var BSON = require('mongodb').BSONPure
var Connection = require('mongodb').Connection;
var Server = require('mongodb').Server;

module.exports = MongoDbProvider;

function MongoDbProvider(host, port) {
    this._db = new Db("screening", new Server(host, port, {auto_reconnect: true}, {}));
    this._db.open(function(err, dbConn) {
        if (err) {
            console.error("Couldn't connect to MongoDB, plese check /docs/MongoDb.md for info on how to setup the MongoDB server", err.message);
            process.exit(1);
        } else {
            console.log("Connected to MongoDB server on " + dbConn.serverConfig.host + ":" + dbConn.serverConfig.port + ", database: " + dbConn.databaseName);
        }
    });

    return this;
github TheDrone7 / Wumpi / src / providers / mongodb.js View on Github external
async init() {
    const connection = mergeDefault(
      {
        conString: `mongodb://127.0.0.1:27017/WumpiDB`
      },
      this.client.options.providers.mongodb
    );

    // If full connection string is provided, use that, otherwise fall back to individual parameters
    const connectionString = connection.conString;

    const mongoClient = await Mongo.connect(
      connectionString,
      mergeObjects(connection.options, { useNewUrlParser: true, useUnifiedTopology: true })
    );

    this.db = mongoClient.db(connection.db);
  }
github logv / snorkel / snorkel / core / server / db.js View on Github external
// TODO: report errors somewhere?
    if (err) { return ; }
    _db = db;
    arbiter.emit("db_open", db);
  }

  if (db_url) {
    var options = {
      uri_decode_auth: true,
      server: server_options,
      db: db_options
    };
    mongodb.connect(db_url, options, onOpened);
  } else {
    var mongoserver = new mongodb.Server(host, port, server_options);
    var db_connector = new mongodb.Db(db_name, mongoserver, db_options);
    db_connector.open(onOpened);
  }

  return {
    get: function() {
      var cb;
      var args = _.toArray(arguments);
      var last = args.pop();

      if (_.isFunction(last)) {
        cb = last;
      } else {
        args.push(last);
      }

      var db_name = args.join(separator);
github adrai / node-queue / lib / databases / mongodb.js View on Github external
if (options.servers && Array.isArray(options.servers)){
      var servers = [];

      options.servers.forEach(function(item){
        if(item.host && item.port) {
          servers.push(new mongo.Server(item.host, item.port, item.options));
        }
      });

      server = new mongo.ReplSetServers(servers);
    } else {
      server = new mongo.Server(options.host, options.port, options.options);
    }

    this.db = new mongo.Db(options.dbName, server, { safe: true });
    this.db.on('close', function() {
      self.emit('disconnect');
    });

    this.db.open(function (err, client) {
      if (err) {
        if (callback) callback(err);
      } else {
        var finish = function (err) {
          self.client = client;
          self.queue = new mongo.Collection(client, options.collectionName);
          // self.queue.ensureIndex({ 'id': 1 }, function() {});
          if (!err) {
            self.emit('connect');
          }
          if (callback) callback(err, self);
github jaystack / jaydata / au / authentication.js View on Github external
//var host1 = 'db1.storm.jaystack.com';
var host1 = 'localhost';
var host2 = 'db2.storm.jaystack.com';
var port = Connection.DEFAULT_PORT;
var server1 = new Server(host1, port, {});
var server2 = new Server(host2, port, {});
var servers = new Array();
//servers[0] = server2;
//servers[1] = server1;
servers[0] = server1;

// username, password mongohoz
var replStat = new ReplSetServers(servers);
//var usersdb = new Db(config.application.id + '-Users', replStat, {native_parser:false});
//var usersdb = new Db('Users', replStat, {native_parser:false});
var usersdb = new Db('ApplicationDB', new Server(host1, port, {}), {native_parser:false});
usersdb.open(function(err, db) {
  console.log('users database opened');
});

function mongoAuthenticate(username, password) {
    var defer = q.defer();
    usersdb.collection('Users', function(err, collection) {
      if (err) defer.reject(err);
      collection.find({Login:username}, function(err, cursor) {
        cursor.toArray(function(err, users) {
          if (err) defer.reject(err);
          if (users.length == 0) defer.reject('No such user');
          else if (users.length > 1) defer.reject('Duplicate user');
          else bcrypt.compare(password, users[0].Password, function(err, ok) {
            if (err) defer.reject(err);
            if (!ok) defer.reject('Invalid password');
github rmeschian / javascript-ecosystem-tutorials / mongodbMapReduceWithNodeJSExample.js View on Github external
// node mongodbMapReduceWithNodeJSExample.js

var mongodb_db = require('mongodb').Db;
var mongodb_connection = require('mongodb').Connection;
var mongodb_server = require('mongodb').Server;

var host = 'localhost';
var port = mongodb_connection.DEFAULT_PORT;
var db = new mongodb_db('sampleDB', new mongodb_server(host, port, {}), {
    native_parser : false
});


// --------------


function init(callback) {
    db.open(function() {
        db.dropCollection('sample', function(err, result) {
            seedData(callback);
        });
    });
}

function seedData(callback) {
github cn007b / my / ed / nodeJs / _ruBookPauersS / mongo4.node.js View on Github external
/*
$inc       Приращение значения поля на конкретную величину.
$set       Устанавливает поле, как было показано в предыдущем примере.
$unset     Удаление поля
$push      Добавление значения к массиву, если поле является массивом (с преобразованием поля в массив, если поле им не является).
$pushAll   Добавление нескольких значений к массиву.
$addToSet  Добавление к массиву, только если поле является массивом.
$pull      Удаление значения из массива.
$pullAll   Удаление из массива нескольких значений.
$rename    Переименование поля.
$bit       Выполнение поразрядной операции.
*/
var mongodb = require('mongodb');
var server = new mongodb.Server('localhost', 27017, {auto_reconnect: true});
var db = new mongodb.Db('exampleDb', server);
// открытие соединения с базой данных
db.open(function(err, db) {
    if(!err) {
        // доступ к коллекции виджетов или создание этой коллекции
        db.collection('widgets',function(err, collection) {
            // обновление
            collection.update(
                {id:4},
                {$set : {title: 'Super Bad Widget'}},
                {safe: true},
                function(err, result) {
                    if (err) {
                        console.log(err);
                    } else {
                        console.log(result);