2017-06-16 56 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); 
}); 
相關問題