No tienes acceso a esta clase

隆Contin煤a aprendiendo! 脷nete y comienza a potenciar tu carrera

Conectando Mongo a los servicios

12/24
Recursos

Establecida la conexi贸n a la base de datos con Mongoose y creadas las entidades que mapean la informaci贸n, es momento de realizar las consultas a la base de datos desde los servicios.

Ejecutando consultas con Mongoose

Aqu铆 tienes una serie de pasos que te ayudar谩n durante este proceso.

Paso 1: importaci贸n del esquema en los servicios

Comienza inyectando el esquema creado en el servicio que ser谩 el responsable de realizar las consultas.

// modules/products/products.service.ts
import { InjectModel } from '@nestjs/mongoose';
import { Model } from 'mongoose';

@Injectable()
export class ProductsService {

  constructor(@InjectModel(Product.name) private productModel: Model<Product>) {}

  findAll() {
    return this.productModel.find().exec();
  }

  findOne(id: string) {
    return this.productModel.findById(id).exec();
  }
}

Utilizando InjectModel, inyectas el esquema de productos en el servicio de productos.

Paso 2: importaci贸n del servicio en los controladores

Los servicios son los responsables de realizar las consultas a la base de datos, pero los controladores son quienes determinan cu谩ndo hay que realizar esas consultas.

// module/products/products.controller.ts
@Controller('products')
export class ProductsController {

  @Get()
  async getAll() {
    return await this.productsService.findAll();
  }

  @Get(':productId')
  async getOne(@Param('productId') productId: string) {
    return await this.productsService.findOne(productId);
  }
}

Crea tantos endpoints como necesites para responder a la necesidad de obtenci贸n de los datos a trav茅s de GET.
As铆, ya tienes completada tu conexi贸n a la base de datos y obtenci贸n de datos en tu API a trav茅s de Mongoose y sus esquemas.

Contribuci贸n creada por: Kevin Fiorentino (Platzi Contributor).


C贸digo de ejemplo para conectar Mongo a los servicios

// src/products/services/products.service.ts

import { InjectModel } from '@nestjs/mongoose';
import { Model } from 'mongoose';

...

@Injectable()
export class ProductsService {
  constructor(
    @InjectModel(Product.name) private productModel: Model<Product>, // 馃憟
  ) {}
  ...

  findAll() { // 馃憟
    return this.productModel.find().exec();
  }

  async findOne(id: string) {  // 馃憟
    const product = await this.productModel.findById(id).exec();
    if (!product) {
      throw new NotFoundException(`Product #${id} not found`);
    }
    return product;
  }
  ...

}
// src/products/controllers/products.controller.ts

@Controller('products')
export class ProductsController {
   ...

  @Get(':productId')
  getOne(@Param('productId') productId: string) {   // 馃憟
    return this.productsService.findOne(productId);
  }
}
// src/users/services/users.service.ts
@Injectable()
export class UsersService {
  ...

  async getOrderByUser(id: number) {   // 馃憟
    const user = this.findOne(id);
    return {
      date: new Date(),
      user,
      products: await this.productsService.findAll(),   // 馃憟 implement await
    };
  }
}

Aportes 6

Preguntas 4

Ordenar por:

驴Quieres ver m谩s aportes, preguntas y respuestas de la comunidad?

o inicia sesi贸n.

Dejo mi aporte de c贸mo a la vez tener el timestamps en true, en el Shema que quieras, me refiero al createdAt y updatedAt

@Schema({
  timestamps: true,
})

Dejo mi aporte de como me quedaron los entities del modulo de producto

Entities

// products/entities/brand.entity.ts
import { Prop, Schema, SchemaFactory } from '@nestjs/mongoose';
import { Document } from 'mongoose';

@Schema()
export class Brand extends Document {
  @Prop({ required: true })
  name: string;

  @Prop()
  image: string;
}
export const BrandSchema = SchemaFactory.createForClass(Brand);

// products/entities/category.entity.ts
import { Prop, Schema, SchemaFactory } from '@nestjs/mongoose';
import { Document } from 'mongoose';

@Schema()
export class Category extends Document {
  @Prop({ required: true })
  name: string;
}
export const CategorySchema = SchemaFactory.createForClass(Category);

Services

// products/services/brand.service.ts
@Injectable()
export class BrandsService {

  constructor(
    @InjectModel(Brand.name) private brandModel: Model<Brand>,
  ) {}

  findAll() {
    return this.brandModel.find().exec();
  }

  async findOne(id: string) {
    const brand = await this.brandModel.findById(id).exec();
    if (!brand) {
      throw new NotFoundException(`Brand #${id} not found`);
    }
    return brand;
  }
}

// products/services/categories.service.ts
@Injectable()
export class CategoriesService {

  constructor(
    @InjectModel(Category.name) private categoryModel: Model<Category>,
  ) {}

  findAll() {
    return this.categoryModel.find().exec();
  }

  async findOne(id: string) {
    const category = await this.categoryModel.findById(id).exec();

    if (!category) {
      throw new NotFoundException(`Category #${id} not found`);
    }
    return category;
  }
}

Controllers

// products/controllers/brand.controller.ts
@ApiTags('brands')
@Controller('brands')
export class BrandsController {
  constructor(private brandsService: BrandsService) {}

  @Get()
  findAll() {
    return this.brandsService.findAll();
  }

  @Get(':id')
  get(@Param('id') id: string) {
    return this.brandsService.findOne(id);
  }
}

// products/controllers/category.controller.ts
@Controller('categories')
export class CategoriesController {
  constructor(private categoriesService: CategoriesService) {}

  @Get()
  findAll() {
    return this.categoriesService.findAll();
  }

  @Get(':id')
  get(@Param('id') id: string) {
    return this.categoriesService.findOne(id);
  }
}

Este curso vale oro. Est谩 excelente

Amo este curso uwu.

Aqu铆 mi endpoint de user funcionando

Estoy haciendo un api para un creador de paginas tipo wordpress con react y lo combine con esta api, asi quedo mi modelo

import { Injectable , Inject } from '@nestjs/common';
import { InjectModel } from '@nestjs/mongoose';
import { Model } from 'mongoose';
import { Page, PageDocument } from 'src/schema/page.schema';
import { CreatePageDTO } from '../dtos/page.dto';

@Injectable()
export class PageService {
  
  constructor(
    @InjectModel(Page.name) private pageModel: Model<PageDocument>,
  ) {}
  
  async createPage( page : CreatePageDTO ) {

    const result = await this.pageModel.findOne({ name: page.name })

    if( result ) return null

    return await new this.pageModel(page).save();

  }

  async getByName(name) {
    
    const doc = await this.pageModel.findOne({ name });
    
    return doc;

  }

  async getAllPages() {
    
    const doc = await this.pageModel.find({}, { name: 1 });
    
    return doc;

  }


  }
  
}