A
A
Andrey Ivanov2020-09-23 13:22:39
Mongoose
Andrey Ivanov, 2020-09-23 13:22:39

How to do populate and select correctly?

5f6b21db89ebe104340769.png

It is necessary to write in the query string, for example, ?select=firstSection and thus the request for getting will return only what was in the document in the firstSection field.
It's easy, select("firstSection")

But when I do everything that I described in the first paragraph and at the same time I get the whole image document canIHelpSection.directionsOfDevelopment.img I need to do a populace. And so I populate and it turns out that the whole canIHelpSection is given to me, but despite the fact that I don’t request it, select('firstSection') says

Answer the question

In order to leave comments, you need to log in

2 answer(s)
H
hzzzzl, 2020-09-23
@hzzzzl

in order for me to get the entire image document canIHelpSection.directionsOfDevelopment.img I need to make a populace.
And so I do a populace and it turns out that the entire canIHelpSection is given to me, but despite the fact that I do not request it, it is written in select ('firstSection')

so what should be the end result? firstSection or "whole image document canIHelpSection.directionsOfDevelopment.img"

A
Andrey Ivanov, 2020-09-23
@newdecline

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;
  }
}

In order for documents containing information about pictures to be available to me, I make a populate for different fields. However, if I do
await this.homepageModel.findOne(тут все что написано выше).select('firstSection');
await this.homepageModel.findOne(тут все что написано выше).select('canIHelpSection')

then in the first case, the first section will be returned to me and + everything that I have populated,
then in the second case, the section "How can I help" and + everything that I have populated will be returned to me, but I just need to return what is in select ()

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question