mongoose
モンゴースミドルウェア
サーチ…
備考
マングースでは、 ミドルウェアとしても呼ばれpreおよびpostのフック。
ミドルウェアには2種類あります
これらのミドルウェアサポート前後のフックの両方。
ドキュメントミドルウェア
ドキュメント関数
initサポート、validate、save、remove
クエリミドルウェア
クエリ関数
count、find、findOne、findOneAndRemove、findOneAndUpdate、insertMany、updateに対してサポートされています。
プリフックとポストフック
前のフックの2種類があります。
シリアル
名前が示すように、それは連続して実行されます。
平行
並列ミドルウェアはより細かいフロー制御を提供し、すべての並列ミドルウェアによって
doneが呼び出されるまで、hooked methodは実行さ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` );
}
);