# @rxstack/mongoose-service

> RxStack Mongoose Service

Latest version **0.8.2** (published 2024-10-29) · MIT license · 0 weekly downloads

## Install

```sh
npm install @rxstack/mongoose-service
pnpm add @rxstack/mongoose-service
yarn add @rxstack/mongoose-service
bun add @rxstack/mongoose-service
```

## Health

**Score 35/100 (D)** — status: maintenance-mode.

Positive: has types; no vulnerabilities; high quality score.

Warnings: low downloads; no esm support; pre 1.0.

Negative: stale; low maintenance score.

## Facts

| | |
|---|---|
| Version | 0.8.2 |
| Published | 2024-10-29 |
| First published | 2019-01-23 |
| Weekly downloads | 0 |
| License | MIT |
| TypeScript types | bundled |
| Module format | CommonJS |
| Node | >=12 |
| Dependencies | 5 |
| Unpacked size | 36.7 KB |
| Known vulnerabilities | 0 |
| Install scripts | no |
| GitHub stars | 1 |
| Author | Nikolay Georgiev |
| Maintainers | zender |
| Keywords | rxstack, platform, mongodb, mongoose |

## Links

- npm: https://www.npmjs.com/package/@rxstack/mongoose-service
- Repository: https://github.com/rxstack/mongoose-service
- Issues: https://github.com/rxstack/mongoose-service/issues
- npm.io page: https://npm.io/package/@rxstack/mongoose-service

## Dependencies (5)

- [chalk](https://npm.io/package/chalk.md) ^4.1.2
- [mongodb](https://npm.io/package/mongodb.md) ^6.10.0
- [mongoose](https://npm.io/package/mongoose.md) ^8.7.3
- [injection-js](https://npm.io/package/injection-js.md) ^2.4.0
- [reflect-metadata](https://npm.io/package/reflect-metadata.md) ^0.2.2

## Alternatives

- [angular-pipes](https://npm.io/package/angular-pipes.md) — 5.6K weekly downloads
- [@ng-web-apis/midi](https://npm.io/package/@ng-web-apis/midi.md) — 2.6K weekly downloads
- [happn-3](https://npm.io/package/happn-3.md) — 1.6K weekly downloads
- [@opensip-cli/lang-go](https://npm.io/package/@opensip-cli/lang-go.md) — 1.2K weekly downloads
- [mongoose-typescript](https://npm.io/package/mongoose-typescript.md) — 85 weekly downloads

## Recent versions

- 0.8.2 (latest) — 2024-10-29
- 0.8.1 — 2022-02-07
- 0.7.4 — 2022-02-07
- 0.8.0 — 2022-02-04
- 0.7.3 — 2022-02-04
- 0.7.2 — 2021-11-15
- 0.7.1 — 2021-10-18
- 0.7.0 — 2021-03-22
- 0.6.0 — 2020-01-24
- 0.5.0 — 2019-12-05
- 0.4.0 — 2019-08-09
- 0.3.0 — 2019-06-27
- 0.2.0 — 2019-03-29
- 0.1.6 — 2019-03-11
- 0.1.5 — 2019-03-05
- … 5 more at https://npm.io/package/@rxstack/mongoose-service/versions

## README

# The RxStack Mongoose Service

[![Node.js CI](https://github.com/rxstack/mongoose-service/actions/workflows/node.js.yml/badge.svg?branch=master)](https://github.com/rxstack/mongoose-service/actions/workflows/node.js.yml)
[![Maintainability](https://api.codeclimate.com/v1/badges/f4b78bc8f5a0dc0d9915/maintainability)](https://codeclimate.com/github/rxstack/mongoose-service/maintainability)
[![Test Coverage](https://api.codeclimate.com/v1/badges/f4b78bc8f5a0dc0d9915/test_coverage)](https://codeclimate.com/github/rxstack/mongoose-service/test_coverage)

> Mongoose service that implements [@rxstack/platform adapter API and querying syntax](https://github.com/rxstack/rxstack/tree/master/packages/platform#services).

> This adapter also requires a running [MongoDB database server](https://docs.mongodb.com/manual/tutorial/getting-started/#).

## Table of content

- [Installation](#installation)
- [Setup](#setup)
- [Module Options](#module-options)
- [Service Options](#service-options)
- [Usage](#usage)
    - [Create interfaces](#usage-create-interfaces)
    - [Create mongoose schemas](#usage-schemas)
    - [How to use in controller](#usage-controller)
- [Commands](#commands)
    - [Ensure Endexes](#commands-ensure-indexes)
    - [Drop Database](#commands-drop-database)
- [Validation Observer](#validation-observer)


## <a name="installation"></a> Installation

```
npm install @rxstack/mongoose-service --save
```

## <a name="setup"></a>  Setup
`MongooseServiceModule` needs to be registered in the `application`. Let's create the application:

```typescript
import {Application, ApplicationOptions} from '@rxstack/core';
import {MongooseServiceModule} from '@rxstack/mongoose-service';

export const APP_OPTIONS: ApplicationOptions = {
  imports: [
    MongooseServiceModule.configure({
      connection: {
        uri: process.env.MONGO_HOST, // mongodb://localhost:27017/test
        // mongoose options
        options: { }
      },
    })
  ],
  providers: [
    // ...
  ]
};

new Application(APP_OPTIONS).start();
```

## <a name="module-options"></a> Module Options

- `connection.url`: mongodb server uri
- `connection.options`: mongoose options (optional)
- `logger.enabled`: enable query logging (defaults to false)
- `logger.level`: logging level (defaults to debug)

## <a name="service-options"></a> Service Options
In addition to [service base options](https://github.com/rxstack/rxstack/tree/master/packages/platform#services)
we need to set the following options:

- `model`: [mongoose model](https://mongoosejs.com/docs/models.html)

## <a name="usage"></a>  Usage

### <a name="usage-create-interfaces"></a>  Create interfaces
First we need to create `model interface` and `InjectionToken`:

```typescript
import {InjectionToken} from 'injection-js';
import {MongooseService} from '@rxstack/mongoose-service';

export interface Product {
  id: string;
  name: string;
}

export const PRODUCT_SERVICE = new InjectionToken<MongooseService<Product>>('PRODUCT_SERVICE');
```

### <a name="usage-schemas"></a> Create mongoose schemas

```typescript
import { Schema } from 'mongoose';
const { v4: uuid } = require('uuid');

export const productMongooseSchema = new Schema({
  _id: {
    type: String,
    default: uuid
  },
  name: {
    type: String,
    unique: true,
    required: true,
  }
}, {_id: false, versionKey: false });
```

then register the service in the application provides:

```typescript
import {ApplicationOptions} from '@rxstack/core';
import {MongooseService} from '@rxstack/mongoose-service';
import {Connection} from 'mongoose';

export const APP_OPTIONS: ApplicationOptions = {
  // ...
  providers: [
    {
      provide: PRODUCT_SERVICE,
      useFactory: (conn: Connection) => {
        return new MongooseService({
          idField: '_id', defaultLimit: 25, model: conn.model('Product', productMongooseSchema)
        });
      },
      deps: [Connection],
    },
  ]
};
```

### <a name="usage-controller"></a> How to use in controller


```typescript
import {Connection} from 'mongoose';
import {Injectable} from 'injection-js';
import {Http, Request, Response, WebSocket, InjectorAwareInterface} from '@rxstack/core';

@Injectable()
export class ProductController implements InjectorAwareInterface {

  @Http('POST', '/product', 'app_product_create')
  @WebSocket('app_product_create')
  async createAction(request: Request): Promise<Response> {
    // getting connection
    const connection = injector.get(Connection);
   
    // standard use
    const service = this.injector.get(PRODUCT_SERVICE);
    await service.insertOne(request.body);
  }
}
```

[Read more about platform services](https://github.com/rxstack/rxstack/tree/master/packages/platform#services)

## <a name="commands"></a>  Commands
Helpful commands managing your mongoose database

### <a name="commands-ensure-endexes"></a> Ensure Indexes
Makes the indexes in MongoDB match the indexes defined in this model's schema

```bash
npm run cli mongoose:ensure-indexes
```

### <a name="commands-drop-database"></a> Drop databases
Drop databases, collections and indexes for your documents.

```bash
npm run cli mongoose:drop
```

## <a name="validation-observer"></a>  Validation Observer
`ValidationObserver` converts mongoose errors to `BadRequestException`.

In order to return proper validation errors and status code `400 ` we catch the exception and throw `BadRequestException`.
The error messages can be accessed `exception.data['errors']` and implement [`ValidationError[]`](https://github.com/rxstack/rxstack/tree/master/packages/platform/src).

## License

Licensed under the [MIT license](LICENSE).

---
_Source: https://npm.io/package/@rxstack/mongoose-service · Machine-readable twin of the npm.io package page. Health data is recomputed on every publish._
