I am developing a REST API with my colleagues using Express.js and Mongoose.
For some of the Mongoose Model
methods
and statics
we need the Express.js
Request
object as an added context information source, like the authenticated user currently doing the request.
What we currently do is attach a custom property called context
to a Model
's this
context by prototyping Mongoose
's Model
function.
The issue is that we ran into a nasty bug that made us realise that while with Model.methods
, who are called on Model
instances, it works fine.
For Model.statics
, who are called on the Model
"class" which is implemented as a singleton
though, the scope is shared by the whole app meaning that if you have concurrent requests, they will override each-other's this.context
value if you have any async behaviour in the request processing.
Now my question is the following:
- What are the best practices with
Express.js
andMongoose
for keeping and accessing therequest
context inModel.statics
andModel.methods
functions ?
Of course there are some possible hacks to simulate containment like:
Function.bind()
everyModel
function to add the request context.-> This would mean though that if
Model.statics.a()
internally makes a call toModel.statics.b()
, functionb()
wouldn't have athis.context
.Use the
with() {}
statement on therequest
object and call everyModel
function within that scope.-> Which would be pretty dirty and slow.
Create containers with separate scopes with the
vm
standard Node.js module.-> Same as (2), performance would take a big hit.
Any ideas ? Thank you in advance !