You don't have access to this class

Keep learning! Join and start boosting your career

Aprovecha el precio especial y haz tu profesión a prueba de IA

Antes: $249

Currency
$209
Suscríbete

Termina en:

0 Días
18 Hrs
10 Min
51 Seg

¿Qué es Mongoose? Instalación y configuración

10/24
Resources

Using the official MongoDB driver for NestJS is a good way to work and relate these two worlds. But there is a much more professional and user-friendly way that will help you work faster and make fewer mistakes.

What is Mongoose as an ODM?

Mongoose is an ODM (Object Data Modeling) that allows you to map each collection in your MongoDB database through schemas. These will help you access data, perform complex queries and standardize the data structure.

In MongoDB, being NoSQL, you can store whatever you want, in whatever order you want and with whatever structure you want. This is a very bad practice that you have to avoid because it will bring serious problems in the not too distant future in your project. MDGs are here to solve this.

How to install Mongoose

We leave you this series of steps to use Mongoose.

Step 1: Installing Mongoose

In addition to installing Mongoose, NestJS has its own library that will help you create the schemas, inject the services and execute the queries to your database.

npm install --save @nestjs/mongoose mongoose

Step 2: Importing and configuring Mongoose

Import the MongooseModule module and pass it the connection string using, or not, environment variables.

import { MongooseModule } from '@nestjs/mongoose'; @Module({ imports: [ MongooseModule.forRoot( `${process.env.MONGO_CONF}://${process.env.MONGO_USER}:${process.env.MONGO_PASS}@${process.env.MONGO_HOST}/${process.env.MONGO_BBDD}`) ] } ) })export class AppModule { }

This way, you will have done your database connection through Mongoose, instead of using the official driver.


Contributed by: Kevin Fiorentino.

Example code for Mongoose installation

npm install --save @nestjs/mongoose mongoose
// src/database/database.module.tsimport { MongooseModule } from '@nestjs/mongoose'; // 👈 Import@Global() @Module({ imports: [ // 👈MongooseModule.forRootAsync({ // 👈 Implement ModuleuseFactory: (configService: ConfigType<typeof config>) => { const { connection, user, password, host, port, dbName, } = configService.mongo; return { uri: `${connection}://${host}:${port}`, user, pass: password, dbName, }; }, inject: [config.KEY], }), ], providers: [ [ { provide: 'API_KEY', inject: [config.KEY], }, ], exports: ['API_KEY', 'MONGO', MongooseModule], // 👈 add in exports})export class DatabaseModule {}

Contributions 11

Questions 6

Sort by:

Want to see more contributions, questions and answers from the community?

Se me presento un error el cual era:

TypeError: rxjs_1.lastValueFrom is not a function

la solucion para esto, fue cambiar la version de rxjs

npm i rxjs@^7

No olviden pasar como opciones useUnifiedTopology al cliente de mongo.

        const client = new MongoClient(uri, { useUnifiedTopology: true });

Si tienen un error tras importar MongooseModule:

import { MongooseModule } from'@nestjs/mongoose';

Les recomiendo ir al package.json y cambiar la versión de mongodb a:

"mongodb": "^3.6.4",

Luego tienen que borrar la carpeta de mongodb en /node_modules y correr en la terminal el comando:

npm i 

Parece ser un error entre esas dependencias, pero eso soluciona el problema.

yo lo hice la forma que dice la documentacion al usar mongoose,

Primero creando un provider dentro de la carpeta providers crean su archivo database.provider.ts

import * as mongoose from 'mongoose'

export const databaseProviders = [
    {
        provide: 'DATABASE_CONNECTION',
        useFactory: (): Promise<typeof mongoose> => 
            mongoose.connect(`url a tu db`)
    }
]

Luego ese provider lo traen al modulo de database

import { Module } from '@nestjs/common';
import { databaseProviders } from './database.provider';

@Module({
  providers: [...databaseProviders],
  exports: [...databaseProviders],
})
export class DatabaseModule {}

Y listo, con eso ya pueden injectar el servicio DATABASE_CONNECTION para tomar la conexion

Advertencia en la sección Código de ejemplo a la función que se le asigna a use factory le hace falta el async

El curso es muy bueno, seria excelente que lo actualizaran. Para instalar el modulo de mongoose utilicen

npm install --save @nestjs/mongoose mongoose --legacy-peer-deps

En nuevas versiones de mongoose ya sólo necesitarías hacer algo como esto:

npm install --save mongoose
// database.module.ts
import { Module, Global } from '@nestjs/common';
import { ConfigType } from '@nestjs/config';
import mongoose from 'mongoose';
import config from 'src/config';

const API_KEY = '123456789';
const API_KEY_PROD = 'PROD123';

@Global()
@Module({
  providers: [
    {
      provide: 'API_KEY',
      useValue: process.env.NODE_ENV === 'prod' ? API_KEY_PROD : API_KEY,
    },
    {
      provide: 'MONGO',
      useFactory: async (configService: ConfigType<typeof config>) => {
        const { dbUri, dbName } = configService.mongo;
        await mongoose.connect(dbUri, {
          dbName,
        });
        return mongoose.connection.db;
      },
      inject: [config.KEY],
    },
  ],
  exports: ['API_KEY', 'MONGO'],
})
export class DatabaseModule {}

a la fecha de este comentario, tambien podemos usar el modulo de type orm integrado, que incluye un conector para mongo DB: <https://docs.nestjs.com/techniques/database>
Yo tube que poner esa configuración en el app.module para que jalara, si no, explotaba
Configuración actual ![](https://static.platzi.com/media/user_upload/image-23b6105b-f90b-43f5-aeb0-b63a08fab49f.jpg)

👏