mongodb#Collection TypeScript Examples

The following examples show how to use mongodb#Collection. 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: mongo.ts    From peterportal-client with MIT License 6 votes vote down vote up
/**
 * Gets mongo collection object by name
 * @param collectionName Name of collection to retreive
 * @returns Mongo collection object
 */
function getCollection(collectionName: string): Promise<Collection<any>> {
    return new Promise(async (resolve, reject) => {
        try {
            await getDB();
        }
        catch (e) {
            if (process.env.NODE_ENV == 'production') {
                reject(e);
            }
            else {
                resolve(null!);
            }
            return;
        }
        // check if collection exists
        db.listCollections({ name: collectionName })
            .next(function (err, collection) {
                if (err) reject(err);
                if (collection) {
                    resolve(db.collection(collectionName)!);
                }
                else {
                    reject(`Collection ${collectionName} does not exist!`);
                }
            });
    });
}
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: create-indexes-for-collection.ts    From metroline with GNU General Public License v3.0 6 votes vote down vote up
export async function configureIndexesForCollection(collection: Collection, specs: MongoIndexSpec[]) {
  // ensure indexes have a name

  specs
    .filter(spec => !spec.options?.name)
    .forEach(spec => {
      spec.options = {
        ...spec.options,
        name: computeIndexName(spec.fieldOrSpec),
      };
    });

  // create indexes that don't already exist, or modify them

  await Promise.all(
    specs.map(spec => createIndexIfNotExists(spec, collection)),
  );

  // drop indexes that do not exist anymore

  const existingIndexes: IndexSpecification[] = await collection.listIndexes().toArray();
  const indexesToDrop = existingIndexes
    .filter(index => index.name !== '_id_')
    .filter(index => specs.every(spec => spec.options.name !== index.name));

  await Promise.all(
    indexesToDrop.map(({ name }) => {
      logger.info(`Dropping index ${chalk.bold(name)}`);
      return collection.dropIndex(name);
    }),
  );
}
Example #4
Source File: create-indexes-for-collection.ts    From metroline with GNU General Public License v3.0 6 votes vote down vote up
async function createIndexIfNotExists(spec: MongoIndexSpec, collection: Collection) {
  const indexName = spec.options.name;
  const indexNamespace = `${chalk.blue(collection.collectionName)}.${chalk.cyan(indexName)}`;

  const createIndex = () => collection.createIndex(spec.fieldOrSpec, spec.options);

  try {
    await createIndex();
    logger.debug(`Configured index ${indexNamespace}`);
  } catch (e) {
    if (
      e instanceof MongoError
      && (
        e.code === MongoErrorCode.INDEX_OPTIONS_CONFLICT
        || e.code === MongoErrorCode.INDEX_KEY_SPECS_CONFLICT
      )
    ) {
      logger.debug(`Updating index ${indexNamespace}`);

      const existingIndexes: IndexSpecification[] = await collection.listIndexes().toArray();
      const indexWithSameName = existingIndexes.find(value => value.name === spec.options.name);
      if (indexWithSameName) {
        await collection.dropIndex(indexName);
      } else {
        const indexWithSameKey = findIndexWithSameKey(existingIndexes, spec.fieldOrSpec);
        await collection.dropIndex(indexWithSameKey.name);
      }

      logger.debug(`Updated index ${indexNamespace}`);

      await createIndex();
    } else {
      throw e;
    }
  }
}
Example #5
Source File: Store.ts    From majsoul-api with MIT License 5 votes vote down vote up
public playersCollection: Collection<Player<ObjectId>>;
Example #6
Source File: Store.ts    From majsoul-api with MIT License 5 votes vote down vote up
public configCollection: Collection<Config<ObjectId>>;
Example #7
Source File: member.context.ts    From master-frontend-lemoncode with MIT License 5 votes vote down vote up
getMemberContext = (): Collection<Member> => {
  const db = getDBInstance();
  return db.collection<Member>('members');
}
Example #8
Source File: Store.ts    From majsoul-api with MIT License 5 votes vote down vote up
public sessionsCollection: Collection<Session<ObjectId>>;
Example #9
Source File: Store.ts    From majsoul-api with MIT License 5 votes vote down vote up
public gameCorrectionsCollection: Collection<GameCorrection<ObjectId>>;
Example #10
Source File: Store.ts    From majsoul-api with MIT License 5 votes vote down vote up
public gamesCollection: Collection<GameResult<ObjectId>>;
Example #11
Source File: Store.ts    From majsoul-api with MIT License 5 votes vote down vote up
public userCollection: Collection<User<ObjectId>>;
Example #12
Source File: Store.ts    From majsoul-api with MIT License 5 votes vote down vote up
public contestCollection: Collection<Contest<ObjectId>>;
Example #13
Source File: survey-routes.test.ts    From clean-ts-api with GNU General Public License v3.0 5 votes vote down vote up
accountCollection: Collection
Example #14
Source File: survey-routes.test.ts    From clean-ts-api with GNU General Public License v3.0 5 votes vote down vote up
surveyCollection: Collection
Example #15
Source File: survey-result-routes.test.ts    From clean-ts-api with GNU General Public License v3.0 5 votes vote down vote up
accountCollection: Collection
Example #16
Source File: survey-result-routes.test.ts    From clean-ts-api with GNU General Public License v3.0 5 votes vote down vote up
surveyCollection: Collection
Example #17
Source File: login-routes.test.ts    From clean-ts-api with GNU General Public License v3.0 5 votes vote down vote up
accountCollection: Collection
Example #18
Source File: survey.test.ts    From clean-ts-api with GNU General Public License v3.0 5 votes vote down vote up
accountCollection: Collection
Example #19
Source File: survey.test.ts    From clean-ts-api with GNU General Public License v3.0 5 votes vote down vote up
surveyCollection: Collection
Example #20
Source File: survey-result.test.ts    From clean-ts-api with GNU General Public License v3.0 5 votes vote down vote up
accountCollection: Collection
Example #21
Source File: survey-result.test.ts    From clean-ts-api with GNU General Public License v3.0 5 votes vote down vote up
surveyCollection: Collection
Example #22
Source File: login.test.ts    From clean-ts-api with GNU General Public License v3.0 5 votes vote down vote up
accountCollection: Collection
Example #23
Source File: survey-result-mongo-repository.spec.ts    From clean-ts-api with GNU General Public License v3.0 5 votes vote down vote up
accountCollection: Collection
Example #24
Source File: survey-result-mongo-repository.spec.ts    From clean-ts-api with GNU General Public License v3.0 5 votes vote down vote up
surveyResultCollection: Collection
Example #25
Source File: survey-result-mongo-repository.spec.ts    From clean-ts-api with GNU General Public License v3.0 5 votes vote down vote up
surveyCollection: Collection
Example #26
Source File: survey-mongo-repository.spec.ts    From clean-ts-api with GNU General Public License v3.0 5 votes vote down vote up
accountCollection: Collection
Example #27
Source File: survey-mongo-repository.spec.ts    From clean-ts-api with GNU General Public License v3.0 5 votes vote down vote up
surveyResultCollection: Collection
Example #28
Source File: survey-mongo-repository.spec.ts    From clean-ts-api with GNU General Public License v3.0 5 votes vote down vote up
surveyCollection: Collection
Example #29
Source File: log-mongo-repository.spec.ts    From clean-ts-api with GNU General Public License v3.0 5 votes vote down vote up
errorCollection: Collection