0
votes

Given this simple snippet, I can easily append to my find query an additional parameter of iid. How might you accomplish this same type of hook inside of a middleware?

// SchemaFile.js
import mongoose, {Schema} from 'mongoose'
export const ServiceSchema = new Schema({
  displayName: String,
  iid: String
})

// This works great, but `iid` needs to be dynamic
ServiceSchema.pre('find', function(done) {
  this.find({iid: 'hard_coded'})
  done()
})

// SomeMiddleware.js
import {ServiceSchema} from 'SchemaFile'
app.use(function(req, res, next) {
  ServiceSchema.pre('find', function(done) {
    this.find({iid: res.locals.iid})
    done()
  })
  next()
})

I have found that the middleware never actually runs the pre hook when setup like this. Is this sort of thing possible?

1

1 Answers

1
votes

This code:

  ServiceSchema.pre('find', function(done) {
    this.find({iid: res.locals.iid})
    done()
  })

Does not actually run the pre hook, it just registers it. So every time that middleware is executed, you're just re-registering the same hook. The hook is only executed when you call yourModel.find(). The pre hook, only has access to whatever is inside that model instance, which of course, does not include the req object. So to answer your question, it's not really possible to do what you're trying to do using the pre hook without elaborate hacks.

Also, as someone who has used Mongoose extensively, I recommend to stay away from pre hooks altogether. Just keep that logic in your service layer. You might end up writing more code upfront, but your implementation won't crack as soon as you inevitably need to access some data outside of the model.