250x250
Notice
Recent Posts
Recent Comments
- Today
- Total
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | 4 | 5 | 6 | 7 |
8 | 9 | 10 | 11 | 12 | 13 | 14 |
15 | 16 | 17 | 18 | 19 | 20 | 21 |
22 | 23 | 24 | 25 | 26 | 27 | 28 |
29 | 30 |
Tags
- moment
- single quote
- mongodb
- clipBehavior
- atlas
- findByIdAndDelete
- certbot
- TailwindCSS
- JavaScript
- AWS
- Nodejs
- wil
- mongoose
- css
- MYSQL
- jsonwebtoken
- sequelize
- Express
- til
- flutter
- RDS
- TypeScript
- Node.js
- double quote
- Find
- https
- async
- await
- EC2
- nginx
Link
Archives
기억 휘발 방지소
[Node.js / mongoose] findByIdAndUpdate로 수정을 해보자 본문
728x90
반응형
📌 findByIdAndUpdate를 쓰지 않고 수정하기
title과 description을 수정할거다.
findById()로 DB에서 문서들을 가져오고
post.title = title;
post.description = description; 으로 수정하려고하는 값들을 바꿔주고
post.save()를 해준다.
export const postEdit = async (req, res) => {
const { id } = req.params;
const { title, description } = req.body;
const post = await Post.findById(id);
// 수정
post.title = title;
post.description = description;
await post.save();
...
};
📌 findByIdAndUpdate를 써서 수정하기
findByIdAndUpdate를 쓰면 아래 코드처럼 쓸 수 있다.
일단 findById로 DB에서 검색할 필요가 없다.
그리고 findByIdAndUpdate는 두 개의 인자가 필요한데 첫 번째 인자는 업데이트 하고자 하는 문서의 id, 두 번째 인자는 업데이트 할 정보 혹은 내용이 들어간다.
export const postEdit = async (req, res) => {
const { id } = req.params;
const { title, description } = req.body;
...
await Post.findByIdAndUpdate(id, {
title: title,
description: description,
});
...
};
728x90
반응형
'Database > ODM' 카테고리의 다른 글
[Node.js / mongoose] populate() (0) | 2021.09.28 |
---|---|
[Node.js / mongoose] findByIdAndDelete로 삭제 (0) | 2021.09.21 |
[Node.js / mongoose] findOne, findById로 검색을 해보자 (0) | 2021.09.20 |
[Node.js / mongoose] mongoDB에 저장을 해보자 (0) | 2021.09.20 |
[Node.js / mongoose] Model.find() 검색하기 (0) | 2021.09.18 |