Reputation: 11647
I am trying to build a simple express app with a mongodb database. Here are some lines of code that I am a bit confused about:
var mongo = require('mongodb');
var monk = require('monk');
var db = monk('localhost:27017/nodetest1');
// Make our db accessible to our router
app.use(function(req,res,next){
req.db = db;
next();
});
app.use('/', routes);
app.use('/users', users);
So I am using monk to communicate with my database that is running on localhost:27017. That I get.
What is the app.use doing? I read this explanation:
We already defined "db" when we added Mongo and Monk to app.js. It's our Monk connection object. By adding this function to app.use, we're adding that object to every HTTP request (ie: "req") our app makes. Note: this is probably sub-optimal for performance but, again, we're going quick-n-dirty here.
What does this mean? What are some http requests that I can make?
It seems to allow me to do something like this in a routes file:
router.get('/userlist', function(req, res) {
var db = req.db;
var collection = db.get('usercollection');
collection.find({},{},function(e,docs){
res.render('userlist', {
"userlist" : docs
});
});
});
So I guess when my router makes a get request to /userlist... I have access to the request and response variables. That request variable has a db attached to it? What are the request and response variables?
-Jeff
Upvotes: 1
Views: 313
Reputation: 2976
Express uses something called a chain of responsibility. Basically, every HTTP request coming into the application goes through all the handlers registered with app.use
, app.get
, or similar. They are executed in the order they were registered, and only the handlers matching the request URL are selected.
app.use(function(req,res,next){
req.db = db;
next();
});
This means that the above code registers a handler that:
req.db
(on the object representing the HTTP request)next()
which does exactly what it says - let's the next handler handle the requestThe next handler in that case will be one of the "real" handlers that produce responses, and since your DB handler executed first, the req.db
reference will already be available.
Upvotes: 2