1. Mongoose 구조 복습
// 1. model.js 에서 new mongoose.Schema() method로 Schema 정의
// 2. model.js 에서 module.exports = mongoose.model('Collection이름', 정의Schema)로 연결
// 3. controller.js에서 async함수 생성 -> await 생성 -> CRUD methods
// 4. 맨날쓰는 pattern
router.post('url', async (req, res)=>{
const user = new User(req.body) // 받아온 데이터 객체 생성
try{
await findSomething();
await CRUDSomething();
res.send('sendSomething');
}
catch(e) {
console.log(e)
res.status(400).send(`${e} is error`)
}
})
2. Complex methods and Queries
- 몽구스의 진짜배기는 강력한 쿼리메소드에 있다.
// CRUD methods
const nameKyle = {name:'Kyle'}
const user1 = await User.findById('ID'); // is useful 아이디로 찾기
const user2 = await User.find(nameKyle) // 찾기
const user3 = await User.exists(nameKyle) //true of false 존재하니 ?
const user4 = await User.updateOne(nameKyle, 바꿀내용) //useful
const user5 = await User.deleteOne(nameKyle) //useful
// Queries
const user6 = await User.where('name').equals('Kyle')
const user7 = await User.where('age').gt('12').where('name').equals('Kyle') // age is greater than 12, name is equal to Kyle chaining
const user8 = await User.where('age').lt('31').where('name').equals('Kyle').limit(3).select('age') // age is less than 31, name is equal to Kyle, limit 3 data + returns only selected data age
const user9 = await User.where('age').lt('31').populate('bestFrined') //populate method
// .where() 이건 쿼리를 반환한다.
// 더 다양한 쿼리들이 있다.
- 유튜버 카일님한테 배웠다. 근데 잘생겨서 좀 빡침.
- 근데 영어다 ㅎ
'더이상 하지 않는 Backend - NodeJS > Node-Express 개론(완)' 카테고리의 다른 글
[O'REILLY] Node & Express - 1장 : EXPRESS에 대하여 (0) | 2023.03.06 |
---|---|
Express - 5장 : Authentication - 1 (Session-based Auth) (0) | 2023.03.03 |
Express - 4장 : Mongoose 의 CRUD (0) | 2023.03.03 |
Express - 2장 : MongoDB / Mongoose 세팅하기 (0) | 2023.02.27 |
Express - 1장 : 설치부터 요청처리와 REST API 개념정리 (0) | 2023.02.26 |
댓글