Closed filipows closed 8 years ago
Mongoose middleware doesn't have access to the request object, it is also a separate project for which you can find documentation in their repository.
What you can do, is use our preCreate middleware.
restify.serve(router, model, {
preCreate: function (req, res, next) {
req.body.createdBy = req.user._id
next()
}
})
Hey @Zertz , thanks for your reply.
I cannot find it in Mongoose docs, but I found this and this which shows that it's possible to pass an argument to .save()
method as follow:
var item = new Item();
item.save(req, function() { });
and then access it in pre save hook
:
item.pre('save', function (next, req, callback) {
console.log(req);
next(callback);
});
Maybe it's worth considering to use .save
method on document, rather than .create
as it's presented here?
What do you think?
My highly opiniated view on this is that you should not use req
in your models as it couples your database with your web framework so I would recommend using the method I outlined above.
That said, we could investigate passing req
into save. However, I'm curious as to what happens in the case of async middleware.
Ok, it seems reasonable for me (at least for now ;) ). Thank you for your time!
Hey @Zertz , thanks for your reply.
I cannot find it in Mongoose docs, but I found this and this which shows that it's possible to pass an argument to
.save()
method as follow:var item = new Item(); item.save(req, function() { });
and then access it in
pre save hook
:item.pre('save', function (next, req, callback) { console.log(req); next(callback); });
Maybe it's worth considering to use
.save
method on document, rather than.create
as it's presented here? What do you think?
This solution works with pre-hook but not with post-hook. On passing argument in .save()
, the post hook does not even get called.
So, do you have any idea about how we can access request object(or any other object) in post hook.
Can I somehow add
req.user._id
to document before saving it.Something like:
Do you know if it is possible to achieve something like that?