node / mongoose: getting to request-context in mongoose middleware

前端 未结 3 1933
花落未央
花落未央 2020-12-10 07:13

I\'m using mongoose (on node) and I\'m trying to add some additional fields to a model on save by using Mongoose middleware.

I\'m taking the often-used case of want

相关标签:
3条回答
  • 2020-12-10 07:54

    It can be done with 'request-context'. Step to do:

    Install request-context

    npm i request-context --save
    

    In your app/server init file:

    var express = require('express'),
    app = express();
    //You awesome code ...
    const contextService = require('request-context');
    app.use(contextService.middleware('request'));
    //Add the middleware 
    app.all('*', function(req, res, next) {
      contextService.set('request.req', req);
      next();
    })
    

    In you mongoose model:

    const contextService = require('request-context');
    //Your model define
    schema.pre('save', function (next) {
      req = contextService.get('request.req');
      // your awesome code
      next()
    })
    
    0 讨论(0)
  • 2020-12-10 07:55

    I know this is really old question, but i am answering it as I spend half a day trying to figure this out. We can pass extra properties as options as following example -

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

    And in pre update and save access as following -

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

    Thanks,

    0 讨论(0)
  • 2020-12-10 08:10

    You can pass data to your Model.save() call which will then be passed to your middleware.

    // 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);
    });
    

    Unfortunately this doesn't work on embedded schemas today (see https://github.com/LearnBoost/mongoose/issues/838). One work around was to attach the property to the parent and then access it within the embedded document:

    a = new newModel;
    a._saveArg = 'hack';
    
    embedded.pre('save', function (next) {
      console.log(this.parent._saveArg);
      next();
    })
    

    If you really need this feature, I would recommend you re-open the issue that I linked to above.

    0 讨论(0)
提交回复
热议问题