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

前端 未结 3 1939
花落未央
花落未央 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: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,

提交回复
热议问题