Mongoose发现并找到一个中间件无法正常工作

时间:2015-06-03 06:02:21

标签: node.js mongoose find middleware

如果有以下架构和中间件挂钩,但永远不会调用findfindOne挂钩。 saveupdate挂钩按预期工作。根据{{​​3}}文档,这应该是可用的。

// define the schema for our recs model
var recSchema = mongoose.Schema({
  dis: String,  // rec display
  mod: String   // modified date (HAYSTACK FORMAT)
}, {
  strict: false
});

// create the model for recs
var model = recsdb.model('recs', recSchema);

recSchema.pre('save', function(next) {
  this.mod = HDateTime.now(HTimeZone.UTC).toZinc();
  next();
});
recSchema.pre('update', function(next) {
  this.mod = HDateTime.now(HTimeZone.UTC).toZinc();
  next();
});
recSchema.pre('find', function() {
  console.log("Pre Find");
});
recSchema.pre('findOne', function() {
  console.log("Pre Find One");
});
recSchema.post('find', function() {
  console.log("Post Find");
});
recSchema.post('findOne', function() {
  console.log("Post Find One");
});

1 个答案:

答案 0 :(得分:8)

问题最终成为了物品的顺序。显然,您必须在设置查找挂钩后定义模型。但是,保存和更新挂钩不需要这样做。

// define the schema for our recs model
var recSchema = mongoose.Schema({
  dis: String,  // rec display
  mod: String   // modified date (HAYSTACK FORMAT)
}, {
  strict: false
});

recSchema.pre('save', function(next) {
  this.mod = HDateTime.now(HTimeZone.UTC).toZinc();
  next();
});
recSchema.pre('update', function(next) {
  this.mod = HDateTime.now(HTimeZone.UTC).toZinc();
  next();
});
recSchema.pre('find', function(next) {
  console.log("Pre Find");
  next();
});
recSchema.pre('findOne', function(next) {
  console.log("Pre Find One");
  next();
});
recSchema.post('find', function(doc) {
  console.log("Post Find");
});
recSchema.post('findOne', function(doc) {
  console.log("Post Find One");
});

// create the model for recs
var model = recsdb.model('recs', recSchema);