Ecosyste.ms: Awesome

An open API service indexing awesome lists of open source software.

Awesome Lists | Featured Topics | Projects

https://github.com/tony133/nestjs-mongodb-driver

MongoDB Node Driver module for Nest framework (node.js) 😻
https://github.com/tony133/nestjs-mongodb-driver

javascript mongodb-driver mongodb-native mongodb-native-driver nest nestjs nestjs-mongodb-native-driver typescript

Last synced: 2 months ago
JSON representation

MongoDB Node Driver module for Nest framework (node.js) 😻

Awesome Lists containing this project

README

        


Nest Logo

[circleci-image]: https://img.shields.io/circleci/build/github/nestjs/nest/master?token=abc123def456
[circleci-url]: https://circleci.com/gh/nestjs/nest

A progressive Node.js framework for building efficient and scalable server-side applications.



NPM Version
Package License
NPM Downloads
CircleCI
Coverage
Discord
Backers on Open Collective
Sponsors on Open Collective

Support us


## Description

MongoDB Native Driver module for Nest framework (node.js) 😻

## Installation

First install the module via `yarn` or `npm` or `pnpm` and do not forget to install the driver package as well:

```bash
$ npm i --save nest-mongodb-driver mongodb
```
or

```bash
$ yarn add nest-mongodb-driver mongodb
```
or

```bash
$ pnpm add nest-mongodb-driver mongodb
```

## Table of Contents

- [Description](#description)
- [Table of Contents](#table-of-contents)
- [Usage](#usage)
- [MongoDbDriverModule](#mongodbdrivermodule)
- [MultiConnectionsDatabase](#multi-connections-database)
- [ExampleOfUse](#example-of-use)

## Usage

### MongoDbDriverModule

MongoDbDriverModule is the primary entry point for this package and can be used synchronously

```typescript
@Module({
imports: [
MongoDbDriverModule.forRoot({
url: 'mongodb://localhost:27017/[:nameDb]',
}),
],
})
```

or asynchronously

```typescript
@Module({
imports: [
MongoDbDriverModule.forRootAsync({
useFactory: () => ({
url: 'mongodb://localhost:27017/[:nameDb]',
}),
}),
],
})
```

## Example of use

UsersService:

```typescript
import { Injectable } from '@nestjs/common';
import { Db, ObjectId } from 'mongodb';
import { InjectClient } from 'nest-mongodb-driver';
import type {
Document,
} from 'mongodb';

@Injectable()
export class UsersService {
constructor(@InjectClient() private readonly db: Db) {}

async findAll(): Promise {
return await this.db.collection('users').find().toArray();
}
}
```

UsersController:

```typescript
import { Controller, Get } from '@nestjs/common';
import { UsersService } from './users.service';
import type {
Document,
} from 'mongodb';

@Controller()
export class UsersController {
constructor(private readonly usersService: UsersService) {}

@Get()
async getAllUsers(): Promise {
return await this.usersService.findAll();
}
}
```

## Multi Connections Database

```typescript
@Module({
imports: [
MongoDbDriverModule.forRootAsync(
{
useFactory: () => ({
url: 'mongodb://localhost:27017/test1',
}),
},
'db1Connection',
),
MongoDbDriverModule.forRootAsync(
{
useFactory: () => ({
url: 'mongodb://localhost:27018/test2',
}),
},
'db2Connection',
),
],
controllers: [],
providers: [],
})
export class AppModule {}
```

Usage example with Multi Connection

PostService:

```typescript
@Injectable()
export class PostService {
constructor(
@InjectConnection('db2Connection')
private dbConnection: Db,
) {}

public async findAll(): Promise {
return await this.dbConnection.collection('posts').find().toArray();
}

public async create(createPostDto: CreatePostDto): Promise> {
try {
return await this.dbConnection
.collection('posts')
.insertOne(createPostDto);
} catch (err) {
throw new HttpException(err, HttpStatus.BAD_REQUEST);
}
}
```

UsersService:

```typescript
@Injectable()
export class UsersService {
constructor(
@InjectConnection('db1Connection')
private dbConnection: Db,
) {}

public async findAll(): Promise {
return await this.dbConnection.collection('users').find().toArray();
}

public async create(createUserDto: CreateUserDto): Promise> {
try {
return await this.dbConnection
.collection('users')
.insertOne(createUserDto);
} catch (err) {
throw new HttpException(err, HttpStatus.BAD_REQUEST);
}
}
}
```

For more information on `MongoDB NodeJS Driver` see [here](https://www.mongodb.com/docs/drivers/node/current/)

## Contribute
Feel free to help this library, I'm quite busy with also another Nestjs packages, but the community will appreciate the effort of improving this library. Make sure you follow the guidelines

## Stay in touch

- Author - [Tony133](https://github.com/Tony133)
- Framework - [https://nestjs.com](https://nestjs.com/)

## License

[MIT licensed](LICENSE)