2017-06-16 53 views
0

我需要从后中间获取文档ID,但是当findAndUpdate时它不存在。使用前/保存中间件Mongoose模型方法时获取文档ID

任何人都知道为什么?

const mongoose = require('mongoose'), 
     Schema = mongoose.Schema, 
     ShiftSchema = new Schema({ 
     _id: { type: String, 'default': shortid.generate}, 
     creator_id: { type: String, required: true }, 
     project_id: { type: String, required: true } 
     }), 
     _ = require('underscore'); 

var when_to_notify = ['save', 'findByIdAndUpdate', 'findOneAndUpdate', 'findByIdAndUpdate']; 

_.each(when_to_notify, function(pre_func) { 
    ShiftSchema.post(pre_func, function() { 
    otherFunc(this); 
    }); 
}) 

function otherFunc(self) { 
    doSomethingWith(self._id) 
    // typeof self._id == 'undefined' == true 
} 

回答

1

只有一组特定的功能支持的中间件文件和查询功能。

文献中间件支持:

  • 初始化
  • 验证
  • 节省
  • 除去

查询中间件支持这些模型和查询功能:

  • 找到
  • findOne
  • findOneAndRemove
  • findOneAndUpdate
  • insertMany
  • 更新

另一个因素可能是:

查询米iddleware与文档中间件有细微的差别,但重要的方式是:在文档中间件中,这指的是正在更新的文档 。在查询中间件中,猫鼬不一定有 对正在更新的文档的引用,所以这是指查询 对象而不是正在更新的文档。

在您的示例中,您正在将查询和文档中间件与相同的函数进行混合,因此上下文将有所不同。文档中间件签名实际上采用文档参数:

schema.post('save', function(doc) { 
    console.log('%s has been saved', doc._id); 
}); 
相关问题