中间件在保存之前散列用户密码

*这是 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: 'john.doe@gmail.com',
      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` );
  }
);