수색…


비고

몽구스에서는 Middlewaresprepost 고리라고도합니다.

미들웨어에는 두 가지 유형이 있습니다.

이러한 미들웨어 지원 전후 후크 모두.

  1. 문서 미들웨어

    문서 함수 init , validate , saveremove

  1. 미들웨어 쿼리

    쿼리 함수 count , find , findOne , findOneAndRemove , findOneAndUpdate , insertManyupdate 됩니다.


전 후크

프리 훅에는 두 가지 유형이 있습니다

  1. 연속물

    이름에서 알 수 있듯이, 그 순차적 순서대로 실행됩니다.

  1. 평행

    병렬 미들웨어는 더 세분화 된 흐름 제어를 제공하며, 모든 병렬 미들웨어에 의해 done 이 호출 될 때까지 hooked method 는 실행되지 않습니다.

포스트 미들웨어는 후에 실행되는 hooked method 과 그 모든 pre 미들웨어는 완료되었습니다.


후크 방식 은 문서 미들웨어가 지원하는 기능입니다. init, validate, save, remove

저장하기 전에 사용자 암호를 해시하는 미들웨어

이것은 Serial Document Middleware 의 예입니다

이 예에서는 데이터베이스에 저장하기 전에 일반 텍스트 암호를 해시 된 암호로 변환하는 미들웨어를 작성합니다.

이 미들웨어는 새 사용자를 만들거나 기존 사용자 세부 정보를 업데이트 할 때 자동으로 실행됩니다.


FILENAME : User.js

// lets import mongoose first
import mongoose from 'mongoose'

// lets create a schema for the user model
const UserSchema = mongoose.Schema(
  {
    name: String,
    email: { type: String, lowercase: true, requird: true },
    password: String,
  },
);


/**
 * This is the middleware, It will be called before saving any record
 */
UserSchema.pre('save', function(next) {

  // check if password is present and is modified.
  if ( this.password && this.isModified('password') ) {

    // call your hashPassword method here which will return the hashed password.
    this.password = hashPassword(this.password);

  }

  // everything is done, so let's call the next callback.
  next();

});


// lets export it, so we can import it in other files.
export default mongoose.model( 'User', UserSchema );

이제 우리가 사용자를 저장할 때마다이 미들웨어는 암호가 설정 되고 수정 되었는지 확인합니다 (수정되지 않은 경우 사용자 암호를 해시하지 않습니다.).


FILENAME : App.js

import express from 'express';
import mongoose from 'mongoose';

// lets import our User Model
import User from './User';

// connect to MongoDB
mongoose.Promise = global.Promise;
mongoose.connect('mongodb://127.0.0.1:27017/database');


let app = express();
/* ... express middlewares here .... */


app.post( '/', (req, res) => {

  /*
    req.body = {
      name: 'John Doe',
      email: '[email protected]',
      password: '!trump'
    }
   */

  // validate the POST data

  let newUser = new User({
    name: req.body.name,
    email: req.body.email,
    password: req.body.password,
  });

  newUser.save( ( error, record ) => {
    if (error) {
      res.json({
        message: 'error',
        description: 'some error occoured while saving the user in database.'
      });
    } else {
      res.json({
        message: 'success',
        description: 'user details successfully saved.',
        user: record
      });
    }
  });

});



let server = app.listen( 3000, () => {
    console.log(`Server running at http://localhost:3000` );
  }
);


Modified text is an extract of the original Stack Overflow Documentation
아래 라이선스 CC BY-SA 3.0
와 제휴하지 않음 Stack Overflow