florianholzapfel / express-restify-mongoose

Easily restify mongoose databases
https://florianholzapfel.github.io/express-restify-mongoose/
MIT License
640 stars 155 forks source link

[question] Accessing 'req' object in a mongoose middleware #283

Closed filipows closed 8 years ago

filipows commented 8 years ago

Can I somehow add req.user._id to document before saving it.

Something like:

schema.pre('save', function (next) {
  this.createdBy = req.user._id;   // is it possible to access req here?
  next()
})

Do you know if it is possible to achieve something like that?

Zertz commented 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()
  }
})
filipows commented 8 years ago

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?

Zertz commented 8 years ago

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.

filipows commented 8 years ago

Ok, it seems reasonable for me (at least for now ;) ). Thank you for your time!

RahulChouhan96 commented 3 years ago

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.