2014-03-19 23 views
1

我正在使用Q promise庫進行鏈接查詢。我有帖子掛鉤添加到新文檔的新屬性。Mongoosejs在創建後發佈保存

MyModel.create(data) 
      .then(function(data) { 
       // <------------------ post hook has not been triggered yet 
       return MySchema.findById(data._id); // trying to get the new document 
      }) 
     .then(function(data) { 
       // <------------------ post hook has not been triggered yet 
       reply(null, data); // <- my callback 
     }); 
     .done() 
     // <------------------ post hook has triggered!!! 

在創建新文檔後掛鉤不觸發,並在節點控制檯中,我看到它在該鏈結束後觸發。

我可以如何確保在返回新文檔之前創建post hook觸發器?

更新:我的郵件鉤子是異步的,並且貓鼬不會等待它。沒有EventEmitter,沒有其他方式可以使用post hook。

回答

0

您需要堅持原來的承諾d.resolve(),直到post hook完成。

我的意思是實際上等於MyModel.create方法。您返回d.promise,但不解決它。你在那裏等到你的帖子完成後,然後解決承諾。

現在,如何檢查你的郵件鉤子是否完成?我不知道。你可以給它一個回調作爲參數嗎?因此,一旦完成,posthook可以調用此方法,並且您可以解決您的原始承諾。 另一種方法是讓你的.create方法輪詢,或者直到posthook被觸發。

現在,至於爲什麼它不觸發,你還需要顯示更多的代碼。什麼在後面?

+0

當posthook完成時已經制定了發射自定義事件的解決方案。這裏http://pastebin.com/bGh3mPxJ mongoose執行所有鉤子,不要等到它們完成。因此無法知道文檔何時準備就緒。 – Dmytro

相關問題