2012-05-07 34 views
3

我正在使用mongoose(在節點上),我試圖通過使用Mongoose中間件將一些其他字段添加到保存的模型上。node/mongoose:在貓鼬中間件上獲取請求上下文

我正在採取經常使用的情況下想添加lastmodifiedsince日期。 但是,我也想自動添加已完成保存的用戶的名稱/配置文件鏈接。

schema.pre('save', function (next) { 
    this.lasteditby=req.user.name; //how to get to 'req'? 
    this.lasteditdate = new Date(); 
    next() 
}) 

我使用護照 - http://passportjs.org/ - 其導致req.user存在,當然req作爲http請求。

感謝

編輯

我定義的嵌入式架構pre,而我打電話的嵌入式實例該父save。下面發佈的解決方案(通過arg作爲第一個保存參數)適用於非嵌入式案例,但不適用於我的案例。

回答

9

您可以將數據傳遞給您的Model.save()調用,然後傳遞給您的中間件。

// in your route/controller 
var item = new Item(); 
item.save(req, function() { /*a callback is required when passing args*/ }); 

// in your model 
item.pre('save', function (next, req, callback) { 
    console.log(req); 
    next(callback); 
}); 

不幸的是,今天嵌入式模式不適用(見https://github.com/LearnBoost/mongoose/issues/838)。一個解決是屬性附加到父,然後嵌入文檔中訪問:

a = new newModel; 
a._saveArg = 'hack'; 

embedded.pre('save', function (next) { 
    console.log(this.parent._saveArg); 
    next(); 
}) 

如果你真的需要這個功能,我建議你重新打開我聯繫上面的問題。

+0

我應該補充說,我定義'預嵌入式架構,而我調用保存在'嵌入式父'。您的解決方案適用於普通文檔,但不適用於我所描述的嵌入式案例。我已經更新了我的問題以反映這一點,現在我知道它很重要。無論如何,因爲它回答了我的不完整的問題 –

+0

沒關係:https://github.com/LearnBoost/mongoose/issues/838 –

+0

是的,這就是我剛更新答案讓你知道。 – Bill

1

我知道這是一個非常古老的問題,但我正在回答,因爲我花了半天的時間試圖弄清楚這一點。我們可以通過額外的屬性選項下面的例子 -

findOneAndUpdate({ '_id': id }, model, { **upsert: true, new: true, customUserId: userId, ipAddress: ipaddress.clientIp** }, function (err, objPersonnel) { 

而在預更新和保存訪問如下 -

schema.pre('findOneAndUpdate', function (next) { 
    // this.options.customUserId, 
    // this.options.ipAddress 
}); 

感謝,

+0

保存方法怎麼樣? – MoDrags