Accessing Express.js request context in Mongoose models Accessing Express.js request context in Mongoose models mongoose mongoose

Accessing Express.js request context in Mongoose models


Hope you are still interested in the answer

What you really want is to mimic java's thread local concept which basically allows you to define something in the context of that thread.

Node is a single threaded environment and it does not provide anything like that but domains. Domains are very useful in providing context for particular set of operations and mimicking thread local storage.

Node js domains will soon be deprecated but similar solutions like continuation-local-storage are available in npm which will solve your purpose

Eg:Create domain in the context of request

app.use(function(req, res, next) {    var reqDomain = domain.create();    reqDomain.run(next);            //here your request context is created});

Now with the use of process.domain, I will be able to access 'data' bound to above created domain anywhere

var d = process.domain              //process.domain is always be available to you while serving the requestd.obj = {};