import { Injectable } from '@nestjs/common'; import { InjectModel } from '@nestjs/mongoose'; import { Model } from 'mongoose'; import { CreateStructureDto } from './dto/create-structure.dto'; import { Structure, StructureDocument } from './schemas/structure.schema'; @Injectable() export class StructuresService { constructor(@InjectModel(Structure.name) private structureModel: Model<StructureDocument>) {} async create(createStructrureDto: CreateStructureDto): Promise<Structure> { const createdStructure = new this.structureModel(createStructrureDto); return createdStructure.save(); } async search(searchString: string): Promise<Structure[]> { return this.structureModel.find({ $text: { $search: searchString } }).exec(); } async findAll(): Promise<Structure[]> { return this.structureModel.find().exec(); } /** * Count every value occurence of a given key * @param key structure key * @return [{id: 'key', count: 'value'}] */ async countByStructureKey(key: string): Promise<any> { const uniqueElements = await this.structureModel.distinct(key).exec(); return await Promise.all( uniqueElements.map(async (value) => { return { id: value, count: await this.structureModel.countDocuments({ [key]: { $elemMatch: { $eq: value } } }).exec(), }; }) ); } async countByEquipmentsKey(key: string): Promise<any> { return [{ id: key, count: await this.structureModel.countDocuments({ [key]: true }).exec() }]; } }