2012-05-07 100 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