node.js - Node/ Mongoose : getting to request-context in mongoose middleware

标签 node.js 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 作为保存的第一个参数传递)适用于非嵌入式案例,但不适用于我的案例。

最佳答案

您可以将数据传递给您的 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();
})

如果你真的需要这个功能,我建议你重新打开我上面链接的问题。

关于node.js - Node/ Mongoose : getting to request-context in mongoose middleware,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10485302/

相关文章:

node.js - 通过 Node js中的 Mongoose 将一个集合的相同值更改为所需值

Node.js、Express、Mongoose - 输入验证 - 在路由或模型中?

node.js - 如何预加载MongoDB文档?

node.js - Nodejs 中的并发请求处理

javascript - 用于 cpu 密集型操作的 node.js

node.js - Mongoose - 使用 `CastError: Cast to number failed` 时为 "$fieldName"

node.js - 仅在 mongoose 中的填充数组中删除文档 objectid

node.js - 没有使用 mongoose 6 定义的 DEFAULT 的 AuthProvider

javascript - 如何在事件发生后执行测试

javascript - 构建接受文件上传并在其上运行测试的 Node JS 应用程序