newdecline
@newdecline
Front-end-developer

Как правильно делать populate и select?

5f6b21db89ebe104340769.png

Нужно в строку запроса записывать например ?select=firstSection и таким образом запрос на получения отдаст только то что лежало в документе в поле firstSection.
Это легко, select("firstSection")

Но когда я делаю все то что я описал в первом абзаце и при том что бы мне получить весь документ картинки canIHelpSection.directionsOfDevelopment.img мне нужно сделать популейт. И вот я делаю популей и получается что весь canIHelpSection мне отдается, но при том что я его не запрашиваю, в select('firstSection') написано
  • Вопрос задан
  • 85 просмотров
Пригласить эксперта
Ответы на вопрос 2
hzzzzl
@hzzzzl
что бы мне получить весь документ картинки canIHelpSection.directionsOfDevelopment.img мне нужно сделать популейт.

И вот я делаю популейт и получается что весь canIHelpSection мне отдается, но при том что я его не запрашиваю, в select('firstSection') написано


так что надо получить в итоге? firstSection или "весь документ картинки canIHelpSection.directionsOfDevelopment.img"
Ответ написан
Комментировать
newdecline
@newdecline Автор вопроса
Front-end-developer
import { Injectable } from '@nestjs/common';
import { InjectModel } from '@nestjs/mongoose';
import { Model } from 'mongoose';

import { Homepage } from './homapage.schema';
import { UpdateFirstSectionDto } from './dto/update-first-section.dto';
import { UpdateDetailsSectionDto } from './dto/update-details-section.dto';
import { UpdateCanIHelpSectionDto } from './dto/update-can-i-help-section.dto';
import { UpdateQuestionAnswerSectionDto } from './dto/update-question-answer-section.dto';
import { UpdateStepByStepSectionDto } from './dto/update-step-by-step-section.dto';
import { UpdateContactsSectionDto } from './dto/update-contacts-section.dto';
import { UpdatePreFooterSectionDto } from './dto/update-pre-footer-section.dto';
import { UpdateFeedbackSectionDto } from './dto/update-feedback-section.dto';
import { UpdatePortfolioSectionDto } from './dto/update-portfolio-section.dto';
import { FileService } from '../file/file.service';
import { asyncForEach } from '../helpers/asyncForEach';
import { onlyUniqueString } from '../helpers/onlyUniqueString';
import { IDirectionsOfDevelopmentItem } from './interfaces/directions-of-developmentItem.interface';
import { IHomepage } from './interfaces/homepage.interface';
import { IFirstSection } from './interfaces/first-section.interface';
import { IDetailsSection } from './interfaces/details-section.interface';
import { ICanIHelpSection } from './interfaces/can-i-help-section.interface';
import { IQuestionAnswerSection } from './interfaces/question-answer-section.interface';
import { IStepByStepSection } from './interfaces/step-by-step-section.interface';
import { IContactsSection } from './interfaces/contacts-section.interface';
import { IPreFooterSection } from './interfaces/pre-footer-section.interface';
import { IFeedbackSection } from './interfaces/feedback-section.interface';
import { IPortfolioSection } from './interfaces/portfolio-section.interface';

@Injectable()
export class HomepageService {
  constructor(
    @InjectModel(Homepage.name)
    private readonly homepageModel: Model<Homepage>,
    private readonly fileService: FileService,
  ) {}

  async getHomepageData(): Promise<IHomepage> {
    return await this.homepageModel.findOne(
      {},
      '-_id -__v'
      )
      .populate([
        {
          path: 'firstSection',
          populate: {
            path: 'logo',
            model: 'File',
          }
        },
        {
          path: 'canIHelpSection',
          populate: {
            path: 'directionsOfDevelopment.img',
            model: 'File',
          }
        },
        {
          path: 'portfolioSection',
          populate: {
            path: 'portfolio',
            model: 'Portfolio',
            populate: {
              path: 'images',
              model: 'File'
            },
          }
        },
        {
          path: 'feedbackSection',
          populate: {
            path: 'feedback',
            model: 'Feedback',
            populate: {
              path: 'avatar',
              model: 'File'
            },
          }
        },
      ])
      .exec();
  }

  async updateFirstSection(
    updateFirstSectionDto: UpdateFirstSectionDto
  ): Promise<IFirstSection> {
    const { firstSection } = await this.homepageModel.findOne({}, 'firstSection').exec();
    const oldFileId = firstSection.logo;
    const newFileId = updateFirstSectionDto.logo;

    if (newFileId) {
      await this.fileService.checkFileExists(newFileId);
    }

    if (oldFileId && String(oldFileId) !== String(newFileId)) {
      await this.fileService.deleteFile(oldFileId);
    }

    const updatedDocument = await this.homepageModel.findOneAndUpdate(
      {},
      { firstSection: { ...updateFirstSectionDto, logo: newFileId, } },
      { new: true, select: ['firstSection'], projection: '-_id' },
      )
      .exec();

    return updatedDocument.firstSection;
  }
}


Что бы мне были доступны документы содержащие информацию о картинках, я делаю популейт для разных полей. При этом если я выполню
await this.homepageModel.findOne(тут все что написано выше).select('firstSection');
await this.homepageModel.findOne(тут все что написано выше).select('canIHelpSection')

то в первом случае мне вернутся первая секция и + все то что я напопулейтил,
то во втором случае мне вернутся секция "чем я могу помочь" и + все то что я напопулейтил, а нужно только что вернулось то что в select()
Ответ написан
Комментировать
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы