2022-04-18(월) TIL

황인호·2022년 6월 7일
0

TIL 모음

목록 보기
26/119
  • 오늘 해야할일

클론코딩 작성완료된 API 전부 Client tool로 test해보기

  • user.js
  • like.js
  • unlike.js
  • comment.js
  • search.js
  • posts.js

오늘 새롭게 알게된 내용

Clinet tool 사용관련된 내용

하루 정도 골머를 싸매고 알아내려고했던 내용이다...ㅠㅠ

router.post('/subscribe', authMiddleWare, async(req, res) => {
	const {userId} = res.locals.user
	const {userSub, subCheck] = req.body
	console.log(userSub,subCheck)

	if(subCheck) {
		await User.updateOne({userId:userSub}, {$inc:{userSubscribe:-1})
		await Subscribe.deleteOne({userSub, userId})
}else {
		await User.updateOne({userId:userSub},{$inc:{userSubscribe:1})
		await Subscribe.create({userSub,userId})
}

res.status(200).json({result:true})
})

module.exports = router

  • 몰랐던 내용

$inc

연산자는 $inc 지정된 값만큼 필드를 증가시키며 다음 형식을 갖습니다.

{$inc:{<field1>:<amount>,<field2>:<amount>, ...})

또한 $inc는 양수 및 음수 값을 허용합니다.

필드가 없으면 필드를만들고 필드를 지정된 값으로 설정합니다.

$inc는 null 값이 있는 필드에 연산자를 사용하면 오류가 발생합니다.

사용 예시

컬렉션 만들기

db.products.insertOne({
	_id:1,
	sku:"abc123",
	quantity:10,
	metrics:{order:2,ratings:3.5}
})

updateOne()작업은 $inc연산자를 사용합니다.

“metrics.order” 필드를 1씩증가

“quantity” 필드를 -2씩 감소

db.products.updateOne(
	{sku:"abc123"},
	{$inc:{quantity:-2,metrics.order: 1}}
)

이렇게 업데이트된 문서는 아래의 결과를 출력합니다.

{
	_id:1,
	sku:"abc123",
	quantity:8,
	metrics:{order:3,ratings:3.5}
}

$set

연산자는 $set필드 값을 지정된 값으로 바꿉니다.

연산자 표현식의 $set형식을 다음과 같습니다.

{$set:{<field1>:<value1>,...}}

사용예시
db.products.insertOne({
	_id:100,
	quantity:250,
	instock:true,
	reorder:false,
	datails:{model:"14QQ",make:"Clothes Corp"},
	tags: ["apparel","clothing"]
	ratings:[{by:"Customer007", rating:4}]
})

업데이트 요청

db.products.updateOne(
	{_id:100},
	{$set:
		{
			quantity:500,
			details:{model:"2600",make:"Fashionaires"},
			tag:["coats","outerwear","clothing"]
		}
	}
}

위에 업데이트 요청으로인해

quantity의 가치 500

details 새로 포함된 문서가 있는 필드

tags 새 배열이 있는 필드

업데이트 후

{
	_id:100,
	quantity:500,
	instock:true,
	reorder:false,
	details:{model:'2600',make:"Fashionaires"},
	tag:["coats","outerwear","clothing"]
	ratings:[{by:"Customer007",rating:4}]
}

_id:100 일 경우 make필드를 업데이트 합니다.

db.products.updateOne(
	{_id:100},
	{$set:
		{
			"details.make":"Kustom Kidz"
		}
	}
)

업데이트 후 문서의 값은 다음과 같습니다.

{
	_id:100,
	quantity:500,
	instock:true,
	reorder:false,
	details:{model:'2600',make:"Kustom Kidz"}
	tag:["coats","outerwear","clothing"]
	ratings:[{by:"Customer007", rating:4}]
}

배열에 요소 설정하기 tags필드의 값을 업데이트할 경우

db.products.updateOne(
	{_id:100},
	{$set :
		{
			"tags.1":"rain gear",

★Client Tool 활용방법(동선님께 배움 ㅎㅎㅎ)★

음...내가 잘 몰랐던 부분이 const {postNum} = req.query 이다

// 좋아요 기능
router.post("/like", authMiddleware, async (req, res) => {
  try {
    const { postNum } = req.query;
    const { likeCheck, unlikeCheck } = req.body;
    const { userId } = res.locals.user;

    if (likeCheck) {
      await Post.updateOne({ postNum }, { $inc: { postLikeNum: -1 } });
      await Like.deleteOne({ postNum, userId });
    } else {
      await Post.updateOne({ postNum }, { $inc: { postLikeNum: 1 } });
      await Like.create({ postNum, userId });
      if (unlikeCheck) {
        await Post.updateOne({ postNum }, { $inc: { postUnlikeNum: -1 } });
        await Unlike.deleteOne({ postNum, userId });
      }
    }

    res.status(200).json({ result: true });
  } catch (error) {
    console.log(error);
    console.log("likes.js 좋아요에서 에러남");

    res.status(400).json({ result: false });
  }
});

드디어 렌더링에대한 정확한 정의와 의미를 알게되었다

  • 렌더링이란?! 렌더링이란 HTML,CSS,자바스크립트로 작성된 문서를 해석해서 브라우저에서 시각적으로 출력하는 것을 말한다. 때로는 서버에서 데이터를 HTML로 변환해서 브라우저에게 전달하는 과정(SSR: Sever Side Rendering)을 가리키기도 한다. 브라우저가 HTML,CSS,자바스크립트를 로드하고 파싱해서 렌더링하는 과정은 38장 브라우저의 랜더링 과정에서 자세히 살펴볼 것이다.
profile
성장중인 백엔드 개발자!!

0개의 댓글