Skip to content

Instantly share code, notes, and snippets.

@ukyo
Created March 14, 2014 00:41
Show Gist options
  • Save ukyo/9540112 to your computer and use it in GitHub Desktop.
Save ukyo/9540112 to your computer and use it in GitHub Desktop.
mongooseのschema.pre('save',...)

Mongoose Middleware v3.8.8の補足。 特に保存するときのpre hook。

var mongoose = require('mongoose'),
    Schema = mongoose.Schema;

// こんなスキーマがあったとして
var schema = new Schema({
  foo: String,
  fooBigrams: [String]
});

// こんなフックを書けるよー
schema.pre('save', function(next) {
  // 中身はthisにある。ドキュメントに書いてないのは気のせい?
  console.log(this);
  // 前処理
  this.foo = normalizeText(this.foo);
  this.fooBigrams = createNgramList(this.foo, 2);
  next();
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment