• 카테고리

    질문 & 답변
  • 세부 분야

    백엔드

  • 해결 여부

    해결됨

관계등록 강의에서 product service 파일의 create 함수 생성시 문법 관련 질문

23.08.09 20:09 작성 23.08.09 20:24 수정 조회수 270

0

해당 강의에서 product service의 create 함수를 아래와 같이 코딩하는 것을 가르쳐주셨는데요.

아래 코드에서

const tags = [...prevTags, ...newTags.indentifiers];

부분에서 prevTags에도 .identifiers가 붙어야 될 것같다는 생각을 했습니다.

prevTags는 this.productsTagsRepository.find 함수를 통해서 찾아오는데, 이는 where 조건문에 의해 name이 tagNames인 것을 찾아내어 productTags의 프로퍼티인 id와 name을 둘다 return 하지 않나요?

이전 조회API를 만드는 강의에서도 find 함수를 통해 id만 가져오는 것이 아닌 다른 칼럼들도 모두 가져왔었습니다.

그런데 prevTags 뒤에 .indentifiers를 붙이니 에러가 뜨더라구요...

분명 조회API 강의에서는 find를 통해 모든 칼럼을 다 가져왔던것 같은데, 왜 이번에는 똑같은 find 함수를 통해 id만 리턴이 되는 건가요?

   async create({ createProductInput }: IProductServiceCreate): Promise<Product> {


    
    const { productSalesLocation, productCategory, productTags, ...product } = createProductInput;

    const result = await this.productsSalesLocationService.create({ productSalesLocation });
    
    const tagNames = productTags.map((el) => el.replace('#', ''));

    const prevTags = await this.productsTagsRepository.find({
      where: { name: In(tagNames) },
    });

    const temp = [];
    tagNames.forEach((el) => {
      const isExist = prevTags.find((prevEl) => el === prevEl.name);
      if (!isExist) temp.push({ name: el });
    });

    const newTags = await this.productsTagsRepository.insert(temp);
    const tags = [...prevTags, ...newTags.identifiers];
    

    const result2 = this.productsRepository.save({
      ...product,
      productSalesLocation: result,
      productCategory: productCategory,
      productTags: tags,
    });

    return result2; 
  }

답변 1

답변을 작성해보세요.

1

안녕하세요! 정욱님!

typeorm에서 find, save 등을 사용하시게 되면 등록/조회된 객체를 반환하게 됩니다!
반면에, insert를 사용하시게 되면 generatedMaps, identifiers 등의 결과를 반환받게 됩니다!
또한, update, delete 역시 마찬가지로 동일하지 않고 약간씩 달라요!

// find, save 등의 메서드
const board = await this.boardRepository.findOne({ where: {id: 1} })
console.log(board) // { id: 1, title: "안녕하세요" }

// insert 등의 메서드
const board = await this.boardRepository.insert({ title: "반갑습니다"})
console.log(board) // { generatedMaps: [...], identifiers: [...], raw: {...} }

이러한 이유에서 insert로 반환 받은 결과에서는 board.identifiers가 가능하였으나,
find, save로 반환 받은 결과에서는 board.id, board.title 은 가능하더라도, identifiers라는건 존재하지 않겠죠?!^^