반응형

https://mongoosejs.com/docs/middleware.html
Mongoose v7.2.1: Middleware
Middleware (also called pre and post hooks) are functions which are passed control during execution of asynchronous functions. Middleware is specified on the schema level and is useful for writing plugins. Mongoose has 4 types of middleware: document middl
mongoosejs.com
몽구스(mongoose)를 미들웨어로 정의하는 방식
- pre
- post
특정 작업 전후로 처리가 가능하다
# pre
구문)
const schema = new Schema({ /* ... */ });
schema.pre('save', function(next) {
// do stuff
next();
});
기존에는 next 함수를 매개변수를 받아서 실행했어야 했는데
최근에 비동기 함수로 처리해서 프로미스로 반환해서 사용한다.
schema.pre('save', function() {
return doStuff().
then(() => doMoreStuff());
});
// Or, in Node.js >= 7.6.0:
schema.pre('save', async function() {
await doStuff();
await doMoreStuff();
});
이제 save 처리가 되면 pre 안에 함수들이 비동기식으로 차례대로 실행된다.
# post
schema.post('save', function(doc) {
console.log('%s has been saved', doc._id);
});
post는 모든 미들웨어가 완료된 이후 실행된다. -> .pre
반응형
'nodejs' 카테고리의 다른 글
[node.js] express 쿠키 보내기, 파서, 서명 (0) | 2023.06.15 |
---|---|
[node.js] express 에러, 비동기 에러 처리 (0) | 2023.06.14 |
[node.js / express] REST API, RESTful API, npm(UUID, method_override) CRUD 구현 (0) | 2023.05.19 |
[node.js / express] 요청 구문 분석하기(get, post) (0) | 2023.05.18 |
[node.js / express] 정적 assets 과 bootstrap 사용, ejs 파일 분할 (0) | 2023.05.17 |