[Mongodb] mongoose CRUD

김민재·2024년 4월 6일

mongodb

목록 보기
8/8

create

async function createProduct(req, res, next) {
try {
 const newProduct = await productModel.create(req.body);
 res.status(401).json(newProduct);
} catch (error) {
 next(error);
}
}

read

// 모든 상품 조회
async function getProducts(req, res, next) {
  try {
    const products = await productModel.find();
    res.status(401).json(products);
  } catch (error) {
    next(error);
  }
}

// rea.params를 이용한 상품 조회
async function getProduct(req, res, next) {
  try {
    const { productId } = req.params;
    const product = await productModel.findById(productId);
    res.status(401).json(product);
  } catch (error) {
    next(error);
  }
}

update

async function updateProduct(req, res, next) {
  try {
    const { productId } = req.params;
    const updateProduct = await productModel.findByIdAndUpdate(
      productId,
      req.body,
      { new: true }
    );
    res.status(200).json(updateProduct);
  } catch (error) {
    next(error);
  }
}

delete

async function daleteProduct(req, res, next) {
  try {
    const { productId } = req.params;
    const deleteeProduct = await productModel.findByIdAndDelete(productId);
    res.status(200).json(deleteeProduct);
  } catch (error) {
    next(error);
  }
}
  • 각 함수마다 exports를 해주고 router에서 경로 설정을 해주고 실행하면 정상 작동된다.
profile
개발 경험치 쌓는 곳

0개의 댓글