쇼핑몰 상품 CRUD 기능 생성.

change up·2023년 11월 10일
0
post-thumbnail
const Product = model('products', ProductSchema);

class ProductModel {
    constructor() {
        this.productProjection = { __v: 0 };
        this.categoryPopulateOption = {
            createdAt: 0,
            updatedAt: 0,
            __v: 0,
        };
    }
  const productModel = new ProductModel();

-> class를 이용해서 모델의 틀을 잡아주고 constructor로 초기값을 설정하여 불필요한 필드값을 정보를 불러올때 제외하여 클라이언트가 처리할 정보의양을 줄여 효율적인 데이터의 복잡성을 줄입니다.

 async create(productInfo) {
      const createdNewProduct = await Product.create(productInfo);
      return createdNewProduct;
  }

->1.Create(생성):create 메쏘드를 이용하여 상품정보가 등록 될 수 있도록 합니다.

    async findByTitle(title) {
        const product = await Product.findOne(
            { productName: title },
            this.productProjection,
        );
        return product;
    }

    async findById(productId) {
        const product = await Product.findOne(
            { _id: productId },
            this.productProjection,
        ).populate('categoryId', this.categoryPopulateOption);
        return product;
    }

    async findOneByCategoryId(categoryId) {
        const product = await Product.findOne(
            { categoryId },
            this.productProjection,
        ).populate('categoryId', this.categoryPopulateOption);
        return product;
    }

    async findAllByCategoryId(categoryId) {
        const products = await Product.find(
            { categoryId },
            this.productProjection,
        ).populate('categoryId', this.categoryPopulateOption);
        return products;
    }

-> 2.Read :(findOne,find) 메쏘드를 사용하여 상품 정보를 조회할 수 있는 read기능을 생성 가능하도록 했습니다.

    async update({ productId, update }) {
        const filter = { _id: productId };
        const option = { returnOriginal: false };

        const updatedProduct = await Product.findOneAndUpdate(
            filter,
            update,
            option,
        );
        return updatedProduct;
    }

-> 3.Update :(findOneAndUpdate) 메쏘드를 사용하여 특정 상품을 찾아서 정보를 업데이트 할 수 있습니다.

    async deleteById(productId) {
        const result = await Product.deleteOne({ _id: productId });
        return result;
    }

-> 4. Delete:(deleteOne) 메쏘드를 사용하여 특정 상품을 찾아 삭제 기능이 가능합니다.

async findAll() {
        const products = await Product.find(
            {},
            this.productProjection,
        ).populate('categoryId', this.categoryPopulateOption);
        return products;
    }

    async findAllBykeyword(keyword) {
        
        const products = await Product.find(
            {
                $or: [
                    { productName: { $regex: keyword, $options: 'i' } },
                    {
                        shortDescription: { $regex: keyword, $options: 'i' },
                    },
                ],
            },
            this.productProjection,
        ).populate('categoryId', this.categoryPopulateOption);
        return products;
    }

     async insertMany(productsArray) {
        const createdNewProducts = await Product.insertMany(productsArray);
        return createdNewProducts;
    }
    

-> 추가적으로 populate를 사용하여 , 카테고리 id 를 참조하여 해당 카테고리에 속한 상품들을 조회 할 수 있는 기능을 생성하였고, MongoDB의 $or 연산자는 productName 또는 shortDescription 필드 중 하나라도 주어진 조건(키워드와 일치하는 경우)에 부합하는 제품을 찾고,

이후에 populate 메소드를 사용하여 이러한 제품에 연관된 카테고리 정보를 추가한후 ,최종적으로 반환되는 제품 정보에 포함시켜 검색결과를 반환하도록 코드를 작성하였습니다.

profile
새싹이

1개의 댓글

comment-user-thumbnail
2024년 1월 1일

아아앙

답글 달기