mongodb#MongoClient TypeScript Examples

The following examples show how to use mongodb#MongoClient. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: utils.ts    From h1z1-server with GNU General Public License v3.0 7 votes vote down vote up
initMongo = async function (
  mongoClient: MongoClient,
  serverName: string
): Promise<void> {
  const debug = require("debug")(serverName);
  const dbName = "h1server";
  await mongoClient.db(dbName).createCollection("servers");
  const servers = require("../../data/defaultDatabase/shared/servers.json");
  await mongoClient.db(dbName).collection("servers").insertMany(servers);
  await mongoClient.db(dbName).createCollection("zone-whitelist");
  const zoneWhitelist = require("../../data/defaultDatabase/shared/zone-whitelist.json");
  await mongoClient
    .db(dbName)
    .collection("zone-whitelist")
    .insertMany(zoneWhitelist);
  debug("h1server database was missing... created one with samples.");
}
Example #2
Source File: mongo-helper.ts    From clean-ts-api with GNU General Public License v3.0 6 votes vote down vote up
MongoHelper = {
  client: null as MongoClient,
  uri: null as string,

  async connect (uri: string): Promise<void> {
    this.uri = uri
    this.client = await MongoClient.connect(uri)
  },

  async disconnect (): Promise<void> {
    await this.client.close()
    this.client = null
  },

  getCollection (name: string): Collection {
    return this.client.db().collection(name)
  },

  map: (data: any): any => {
    const { _id, ...rest } = data
    return { ...rest, id: _id.toHexString() }
  },

  mapCollection: (collection: any[]): any[] => {
    return collection.map(c => MongoHelper.map(c))
  }
}
Example #3
Source File: roll-backwards.spec.ts    From metroline with GNU General Public License v3.0 6 votes vote down vote up
describe('rollBackwards', () => {
  let db: Db;
  let client: MongoClient;

  beforeEach(() => {
    db = {} as any;
    client = {} as any;
  });

  afterEach(() => {
    jest.clearAllMocks();
    jest.restoreAllMocks();
  });

  it('should run migration', async () => {
    await rollBackwards(db, client);
    expect(down).toHaveBeenCalledWith(db, client);
  });
});
Example #4
Source File: db.ts    From another-portfolio with MIT License 6 votes vote down vote up
export async function initDbClient(): Promise<MongoClient> {
  dbClient = await MongoClient.connect(process.env.MONGODB_URI || '', {
    useNewUrlParser: true,
    useUnifiedTopology: true,
    ignoreUndefined: true
  });

  // eslint-disable-next-line no-console
  console.log('✔️   Connected to Database');
  return dbClient;
}
Example #5
Source File: roll-forward.ts    From metroline with GNU General Public License v3.0 6 votes vote down vote up
export async function rollForward(db: Db, client: MongoClient): Promise<void> {
  logger.debug('Rolling forward');
  const migrated: any[] = await up(db, client);
  if (migrated?.length > 0) {
    migrated.forEach(fileName => logger.info(`Migrated ${chalk.bold(fileName)}`));
  } else {
    logger.info('Nothing to migrate');
  }
}
Example #6
Source File: db.ts    From o7 with MIT License 6 votes vote down vote up
// Usage guides:
// https://docs.mongodb.com/drivers/node/usage-examples/findOne
// https://docs.mongodb.com/drivers/node/usage-examples/find
// https://docs.mongodb.com/drivers/node/usage-examples/insertOne
// https://docs.mongodb.com/drivers/node/usage-examples/insertMany
// https://docs.mongodb.com/drivers/node/usage-examples/updateOne
// https://docs.mongodb.com/drivers/node/usage-examples/updateMany
// https://docs.mongodb.com/drivers/node/usage-examples/replaceOne
// https://docs.mongodb.com/drivers/node/usage-examples/deleteOne
// https://docs.mongodb.com/drivers/node/usage-examples/deleteMany
export function getClient(): MongoClient & { getDb: () => Db; } {
  const client = <any>new MongoClient(config.mongo.connectionString, { useNewUrlParser: true, useUnifiedTopology: true });
  client.getDb = () => client.db(config.mongo.database);
  return client;
}
Example #7
Source File: server.ts    From skywalking-nodejs with Apache License 2.0 6 votes vote down vote up
server = http.createServer(async (req, res) => {
  await new Promise((resolve, reject) => {
    MongoClient.connect(`mongodb://root:root@${process.env.MONGO_HOST}:27017`, {useUnifiedTopology: true}, function(err: any, client: any) {
      if (err) {
          res.end(`${err}`);
          resolve(null);
      } else {
        client.db('admin').collection('docs').findOne().then(
          (resDB: any) => {
            res.end(`${resDB}`);
            resolve(null);
            client.close();
          },
          (err: any) => {
            res.end(`${err}`);
            resolve(null);
            client.close();
          },
        );
      }
    });
  });
})
Example #8
Source File: mongo.ts    From attendance-backend with MIT License 6 votes vote down vote up
function connect(callback: any) {
  MongoClient.connect(connectionString, { useUnifiedTopology: true }, (err, client) => {
    if (err) {
      logger.error('Error Connecting to database')
    }

    const db = client.db('attendance')
    mongodb = db
    callback()
  })
}
Example #9
Source File: mutualaidRunner.ts    From ppeforfree with GNU General Public License v3.0 6 votes vote down vote up
mutualaidRunner = async () => {
  const groups = await mutualAidScraper();

  const mongoClient = new MongoClient("mongodb://localhost:27017", {
    useUnifiedTopology: true,
  });
  await mongoClient.connect();
  const db = mongoClient.db("ppeforfree");
  const collection = db.collection("mutualaid-groups-scrapes");

  for (const group of groups) {
    await collection.replaceOne({ _id: group._id }, group, { upsert: true });
  }

  await mongoClient.close();
}
Example #10
Source File: index.ts    From integration-services with Apache License 2.0 6 votes vote down vote up
/**
	 * Connect to the mongodb.
	 *
	 * @static
	 * @param {string} url The url to the mongodb.
	 * @param {string} dbName The name of the database.
	 * @return {*}  {Promise<MongoClient>}
	 * @memberof MongoDbService
	 */
	static async connect(url: string, dbName: string): Promise<MongoClient | undefined> {
		if (MongoDbService.client) {
			return undefined;
		}

		return new Promise((resolve, reject) => {
			const options: MongoClientOptions = {
				useUnifiedTopology: true
			} as MongoClientOptions;

			MongoClient.connect(url, options, function (err: Error, client: MongoClient) {
				if (err != null) {
					logger.error('could not connect to mongodb');
					reject(err);
					return;
				}
				logger.log('Successfully connected to mongodb');
				MongoDbService.client = client;
				MongoDbService.db = client.db(dbName);

				resolve(client);
			});
		});
	}
Example #11
Source File: db.ts    From filecoin-CID-checker with Apache License 2.0 6 votes vote down vote up
export function getDbo(): Promise<Db> {
  if (dbo) return Promise.resolve(dbo)

  prettyLogger.info(
    { uri: DB_CONNECTION.uri, name: DB_CONNECTION.options.dbName },
    `${NS} Initializing DB connection...`,
  )

  return new Promise((resolve, reject) => {
    MongoClient.connect(
      DB_CONNECTION.uri,
      {
        ...DB_CONNECTION.options,
      },
      function (err, db) {
        if (err) {
          prettyLogger.error(err, `${NS} watcher DB connector error`)
          return reject(err)
        }
        dbo = db.db(DB_CONNECTION.options.dbName)

        prettyLogger.info(`${NS} DB connected`)

        return resolve(dbo)
      },
    )
  })
}
Example #12
Source File: zoneserver.ts    From h1z1-server with GNU General Public License v3.0 6 votes vote down vote up
async connectMongo() {
    const mongoClient = (this._mongoClient = new MongoClient(
      this._mongoAddress,
      { maxPoolSize: 50 }
    ));
    try {
      await mongoClient.connect();
    } catch (e) {
      throw debug(
        "[ERROR]Unable to connect to mongo server " + this._mongoAddress
      );
    }
    debug("connected to mongo !");
    // if no collections exist on h1server database , fill it with samples
    const dbIsEmpty =
      (await mongoClient.db("h1server").collections()).length < 1;
    if (dbIsEmpty) {
      await initMongo(mongoClient, debugName);
    }
    this._db = mongoClient.db("h1server");
  }
Example #13
Source File: Store.ts    From majsoul-api with MIT License 6 votes vote down vote up
public async init(username: string, password: string): Promise<void> {
		const url = `mongodb://${username}:${password}@${process.env.NODE_ENV === "production" ? 'majsoul_mongo' : 'localhost'}:27017/?authMechanism=SCRAM-SHA-256&authSource=admin`;
		const client = new MongoClient(url);

		await client.connect();

		console.log("Connected successfully to server");

		const majsoulDb = client.db('majsoul');

		this.contestCollection = await majsoulDb.collection("contests");
		this.gamesCollection = await majsoulDb.collection("games");
		this.gameCorrectionsCollection = await majsoulDb.collection("gameCorrections");
		this.sessionsCollection = await majsoulDb.collection("sessions");
		this.sessionsCollection.createIndex({ scheduledTime: -1 });
		this.playersCollection = await majsoulDb.collection("players");
		this.configCollection = await majsoulDb.collection("config");

		this.contestStream = this.contestCollection.watch().on("change", change => this.contestChangesSubject.next(change));
		this.configStream = this.configCollection.watch().on("change", change => this.configChangesSubject.next(change));
		this.gameStream = this.gamesCollection.watch().on("change", change => this.gameChangesSubject.next(change));
		this.playerStream = this.playersCollection.watch().on("change", change => this.playerChangesSubject.next(change));

		if ((await this.configCollection.countDocuments()) < 1) {
			this.configCollection.insertOne({});
		}

		const oauthDb = client.db('oauth');
		this.userCollection = await oauthDb.collection("users", {});
	}
Example #14
Source File: Db.ts    From vircadia-metaverse with Apache License 2.0 6 votes vote down vote up
// Do the setup of the database.
// Return a Promise for the creation operation that resolved with the MongoClient.
// The operation initializes the global 'BaseClient' and 'Datab' with the latter
//     being the configured database to use with this application (spec'ed in
//     Config.database.db).
export async function setupDB(): Promise<void> {
    // Connection URL docs: https://docs.mongodb.com/manual/reference/connection-string/
    let connectUrl: string;
    if (IsNotNullOrEmpty(Config.database["db-connection"])) {
        // if user supplied a connection string, just use that
        connectUrl = Config.database["db-connection"];
        Logger.debug(`setupDb: using user supplied connection string`);
    }
    else {
        const userSpec = `${Config.database["db-user"]}:${Config.database["db-pw"]}`;
        const hostSpec = `${Config.database["db-host"]}:${Config.database["db-port"]}`;
        let optionsSpec = '';
        if (Config.database["db-authdb"] !== 'admin') {
            optionsSpec += `?authSource=${Config.database["db-authdb"]}`;
        };
        connectUrl = `mongodb://${userSpec}@${hostSpec}/${optionsSpec}`;
        Logger.debug(`setupDb: connecting to DB at: mongodb://USER@${hostSpec}/${optionsSpec}`);
    };

    // Connect to the client and then get a database handle to the database to use for this app
    // This app returns the base client and keeps it in the exported global variable.
    BaseClient = await MongoClient.connect(connectUrl, {
        useUnifiedTopology: true,
        useNewUrlParser: true
    });
    Datab = BaseClient.db(Config.database.db);

    // Do any operations to update database formats
    await DoDatabaseFormatChanges();

    await BuildIndexes();

    return;
}
Example #15
Source File: configure-indexes.ts    From metroline with GNU General Public License v3.0 6 votes vote down vote up
export async function configureIndexes(client: MongoClient, collectionIndexes: { [collectionName: string]: MongoIndexSpec[] }) {
  const db = client.db();
  await Promise.all(
    Object.keys(collectionIndexes)
      .map(async collectionName => {
        const collection = await createCollectionIfNotExists(collectionName, db);
        const indexes = collectionIndexes[collectionName];
        await configureIndexesForCollection(collection, indexes);
      }),
  );
}
Example #16
Source File: readFromMongodb.test.ts    From Nishan with MIT License 6 votes vote down vote up
it(`readFromMongodb`, async () => {
	const extractDataMock = jest.spyOn(NotionSync, 'extractData').mockImplementationOnce(() => ({ views: [] } as any));
	const mongoConnectMock = jest.spyOn(MongoClient.prototype, 'connect').mockImplementationOnce(async () => undefined);
	const collection_strings: string[] = [];
	const mongoDbMock = jest.spyOn(MongoClient.prototype, 'db').mockImplementationOnce(() => {
		return {
			collection: (collection_string: string) => {
				collection_strings.push(collection_string);
				return {
					findOne () {
						return collection_string;
					},
					find () {
						return {
							toArray () {
								return [ collection_string ];
							}
						};
					}
				};
			}
		} as any;
	});

	await NotionSync.Read.fromMongodb('collection_uri');

	expect(mongoConnectMock).toHaveBeenCalledTimes(1);
	expect(mongoDbMock).toHaveBeenCalledTimes(1);
	expect(collection_strings.sort()).toStrictEqual([ 'collection', 'row_pages', 'template_pages', 'views' ]);
	expect(extractDataMock).toHaveBeenCalledWith({
		collection: 'collection',
		views: [ 'views' ],
		row_pages: [ 'row_pages' ],
		template_pages: [ 'template_pages' ]
	});
});
Example #17
Source File: Database.ts    From discord-statuspage-v2 with MIT License 6 votes vote down vote up
async connect (): Promise<void> {
    const mongo = await connect(this.opts.connectionURI, this.opts.options)
      .catch(console.error)

    if (mongo instanceof MongoClient) {
      this.db = mongo.db(this.opts.name)
      this.client = mongo
      this.connected = true
    }
  }
Example #18
Source File: mongodb.ts    From BotANF with GNU General Public License v3.0 6 votes vote down vote up
export async function connect(_logger: any = logger) {
    return new Promise((resolve, reject) => {
        mongoClient?.connect((err: MongoError, client: MongoClient) => {
            if (err) {
                _logger.log(
                    `${err.name}${err.errmsg}`,
                    logLevel.warning,
                    "mongodb"
                );
                reject(err);
            }
            resolve(client);
        });
    });
}
Example #19
Source File: index.ts    From tinyhouse with MIT License 6 votes vote down vote up
export async function connectDatabase(): Promise<Database> {
    const client = await MongoClient.connect(url);

    const db = client.db("main");

    return {
        bookings: db.collection<Booking>("bookings"),
        listings: db.collection<Listing>("listings"),
        users: db.collection<User>("users"),
    };
}
Example #20
Source File: setup-tests.ts    From monkeytype with GNU General Public License v3.0 5 votes vote down vote up
beforeAll(async () => {
  connection = await MongoClient.connect(global.__MONGO_URI__);
  db = connection.db();
});
Example #21
Source File: migrate.spec.ts    From metroline with GNU General Public License v3.0 5 votes vote down vote up
describe('migrate', () => {
  let db: Db;
  let client: MongoClient;

  let rollForward: SpyInstance;
  let rollbackwards: SpyInstance;
  let processExit: SpyInstance;

  beforeEach(() => {
    db = {} as any;
    client = { close: jest.fn().mockReturnValue(Promise.resolve()) } as any;

    rollForward = jest.spyOn(_rollup, 'rollForward').mockReturnValue(Promise.resolve());
    rollbackwards = jest.spyOn(_rollback, 'rollBackwards').mockReturnValue(Promise.resolve());
    processExit = jest.spyOn(process, 'exit').mockImplementation((() => undefined) as any);
  });

  afterEach(() => {
    jest.clearAllMocks();
    jest.restoreAllMocks();
    delete env.METROLINE_MIGRATE_ROLLBACK;
  });

  it('should rollForward', async () => {
    await migrate(client, db);

    expect(rollForward).toHaveBeenCalledWith(db, client);
    expect(rollbackwards).not.toHaveBeenCalled();
  });

  it('should rollBackwards and exit when rollback enabled', async () => {
    env.METROLINE_MIGRATE_ROLLBACK = true;

    await migrate(client, db);

    expect(rollbackwards).toHaveBeenCalledWith(db, client);
    expect(processExit).toHaveBeenCalledWith(0);
    expect(rollForward).not.toHaveBeenCalled();
  });
});
Example #22
Source File: setup-tests.ts    From monkeytype with GNU General Public License v3.0 5 votes vote down vote up
connection: MongoClient
Example #23
Source File: mongo.ts    From peterportal-client with MIT License 5 votes vote down vote up
client = new MongoClient(process.env.MONGO_URL, { useNewUrlParser: true, useUnifiedTopology: true })
Example #24
Source File: db.ts    From monkeytype with GNU General Public License v3.0 5 votes vote down vote up
export async function connect(): Promise<void> {
  const {
    DB_USERNAME,
    DB_PASSWORD,
    DB_AUTH_MECHANISM,
    DB_AUTH_SOURCE,
    DB_URI,
    DB_NAME,
  } = process.env;

  if (!DB_URI || !DB_NAME) {
    throw new Error("No database configuration provided");
  }

  const connectionOptions: MongoClientOptions = {
    connectTimeoutMS: 2000,
    serverSelectionTimeoutMS: 2000,
    auth: !(DB_USERNAME && DB_PASSWORD)
      ? undefined
      : {
          username: DB_USERNAME,
          password: DB_PASSWORD,
        },
    authMechanism: DB_AUTH_MECHANISM as AuthMechanism | undefined,
    authSource: DB_AUTH_SOURCE,
  };

  const mongoClient = new MongoClient(
    (DB_URI as string) ?? global.__MONGO_URI__, // Set in tests only
    connectionOptions
  );

  try {
    await mongoClient.connect();
    db = mongoClient.db(DB_NAME);
  } catch (error) {
    Logger.error(error.message);
    Logger.error(
      "Failed to connect to database. Exiting with exit status code 1."
    );
    process.exit(1);
  }
}
Example #25
Source File: Db.ts    From vircadia-metaverse with Apache License 2.0 5 votes vote down vote up
BaseClient: MongoClient
Example #26
Source File: AlertService.ts    From ethgaswatch with MIT License 5 votes vote down vote up
export async function Connect(): Promise<MongoClient> {
    if (!dbClient) {
        dbClient = await MongoClient.connect(AppConfig.MONGODB_CONNECTIONSTRING, { useNewUrlParser: true });
        console.log("alerts Connected..");
    }

    return dbClient;
}
Example #27
Source File: mongo.ts    From crypto-fees with MIT License 5 votes vote down vote up
db = process.env.MONGO_CONNECTION_STRING
  ? new MongoClient(process.env.MONGO_CONNECTION_STRING, {
      useUnifiedTopology: true,
    })
  : null
Example #28
Source File: database.ts    From one-platform with MIT License 5 votes vote down vote up
mongodbClient = new MongoClient(MONGO_URL)
Example #29
Source File: mongodb.ts    From BotANF with GNU General Public License v3.0 5 votes vote down vote up
mongoClient = new MongoClient(`${process.env.MONGO}`, {
    useNewUrlParser: true,
    useUnifiedTopology: true,
})