npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

nest-mongo-client

v1.0.8

Published

## Description

Downloads

254

Readme

nest-mongo-client

Description

This is a MongoDB module for NestJS, making it easy to inject the MongoDB driver into your project. It's modeled after the official Mongoose module, allowing for asynchronous configuration and such.

Installation

In your existing NestJS-based project:

$ npm install nest-mongo-client mongodb

Usage

Overall, it works very similarly to the Mongoose module described in the NestJS documentation, though without any notion of models. You may want to refer to those docs as well -- and maybe the dependency injection docs too if you're still trying to wrap your head around the NestJS implementation of it.

Simple example

In the simplest case, you can explicitly specify the database URI, name, and options you'd normally provide to your MongoClient using MongoModule.forRoot():

import { Module } from '@nestjs/common'
import { MongoModule } from 'nest-mongo-client'

@Module({
    imports: [MongoModule.forRoot('mongodb://localhost', 'BestAppEver')]
})
export class CatsModule {}

To inject the Mongo Db object:

import { Injectable } from '@nestjs/common'
import { InjectDb, Db } from 'nest-mongo-client'
import { Cat } from './interfaces/cat'

@Injectable()
export class CatsRepository {
    private readonly collection: mongo.Collection

    constructor(@InjectDb() private readonly db: Db) {
        this.collection = this.db.collection('cats')
    }

    async create(cat: Cat) {
        const result = await this.collection.insertOne(cat)

        if (result.insertedCount !== 1 || result.ops.length < 1) {
            throw new Error('Insert failed!')
        }

        return result.ops[0]
    }
}

To inject a collection object:

import { Module } from '@nestjs/common'
import { MongoModule } from 'nest-mongo-client'
import { CatsController } from './cats.controller'
import { CatsService } from './cats.service'

@Module({
  imports: [MongoModule.forFeature(['cats'])],
  controllers: [CatsController],
  providers: [CatsService],
})
export class CatsModule {}

import { Injectable } from '@nestjs/common'
import { InjectCollection, Collection } from 'nest-mongo-client'
import { Cat } from './interfaces/cat'

@Injectable()
export class CatsRepository {
    constructor(@InjectCollection('cats') private readonly catsCollection: Collection) {}

    async create(cat: Cat) {
        const result = await this.catsCollection.insertOne(cat)

        if (result.insertedCount !== 1 || result.ops.length < 1) {
            throw new Error('Insert failed!')
        }

        return result.ops[0]
    }
}

Asynchronous configuration

If you want to pass in Mongo configuration options from a ConfigService or other provider, you'll need to perform the Mongo module configuration asynchronously, using MongoModule.forRootAsync(). There are several different ways of doing this.

Use a factory function

The first is to specify a factory function that populates the options:

import { Module } from '@nestjs/common'
import { MongoModule } from 'nest-mongo-client'
import { ConfigService } from '../config/config.service'

@Module({
    imports: [MongoModule.forRootAsync({
        imports: [ConfigModule],
        useFactory: (config: ConfigService) => {
            uri: config.mongoUri,
            dbName: config.mongoDatabase
        },
        inject: [ConfigService]
    })]
})
export class CatsModule {}

Use a class

Alternatively, you can write a class that implements the MongoOptionsFactory interface and use that to create the options:

import { Module } from '@nestjs/common'
import { MongoModule, MongoOptionsFactory, MongoModuleOptions } from 'nest-mongo-client'

@Injectable()
export class MongoConfigService implements MongoOptionsFactory {
    private readonly uri = 'mongodb://localhost'
    private readonly dbName = 'BestAppEver'

    createMongoOptions(): MongoModuleOptions {
        return {
            uri: this.uri,
            dbName: this.dbName
        }
    }
}

@Module({
    imports: [MongoModule.forRootAsync({
        useClass: MongoConfigService
    })]
})
export class CatsModule {}

Just be aware that the useClass option will instantiate your class inside the MongoModule, which may not be what you want.

Use existing

If you wish to instead import your MongoConfigService class from a different module, the useExisting option will allow you to do that.

import { Module } from '@nestjs/common'
import { MongoModule } from 'nest-mongo-client'
import { ConfigModule, ConfigService } from '../config/config.service'

@Module({
    imports: [MongoModule.forRootAsync({
        imports: [ConfigModule]
        useExisting: ConfigService
    })]
})
export class CatsModule {}

In this example, we're assuming that ConfigService implements the MongoOptionsFactory interface and can be found in the ConfigModule.