Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

nest-mongodb

Package Overview
Dependencies
Maintainers
1
Versions
7
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

nest-mongodb

A NestJS module for the MongoDB driver

  • 6.4.0
  • latest
  • Source
  • npm
  • Socket score

Version published
Weekly downloads
2.8K
increased by96.94%
Maintainers
1
Weekly downloads
 
Created
Source

nest-mongodb

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-mongodb 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-mongodb'

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

To inject the Mongo Db object:

import * as mongo from 'mongodb'
import { Injectable } from '@nestjs/common'
import { InjectDb } from 'nest-mongodb'
import { Cat } from './interfaces/cat'

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

    constructor(@InjectDb() private readonly db: mongo.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-mongodb'
import { CatsController } from './cats.controller'
import { CatsService } from './cats.service'

@Module({
  imports: [MongoModule.forFeature(['cats'])],
  controllers: [CatsController],
  providers: [CatsService],
})
export class CatsModule {}
import * as mongo from 'mongodb'
import { Injectable } from '@nestjs/common'
import { InjectCollection } from 'nest-mongodb'
import { Cat } from './interfaces/cat'

@Injectable()
export class CatsRepository {
    constructor(@InjectCollection('cats') private readonly catsCollection: mongo.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-mongodb'
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-mongodb'

@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-mongodb'
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.

Keywords

FAQs

Package last updated on 20 Jul 2022

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc