I'm developing a RESTful API using Express.js and Mongodb (and the mongoose module for accessing to the db with Schemas). I was looking for the best way of sharing the connection to the Mongo database across the entire Express app in order to not to have a new connection for every single request (It's advised by the web and by other answers on Stackoverflow). I have read about different solutions and I decided to make a try using this architecture:
In server.js (main app file) I have something like this:
var express = require("express");
var bodyParser = require("body-parser");
var logger = require("morgan");
var configuration = require("./configuration.js");
var fs = require("fs");
var HTTPresponses = require("./responses.js");
var mongoose = require("mongoose");
require("./models/user_model.js");
var Users = mongoose.model("Users");
//Connect to Db
mongoose.connect("mongodb://127.0.0.1/test");
//Rest of the code here
As you can see I create a new connection to the database using mongoose and then I require user_module that is something like this:
var UserSchema = new Schema({
name : {type: String},
surname : {type: String},
username : {type: String, unique: true, required: true}
}
,{
collection : "Users"
});
mongoose.model("Users", UserSchema);
This way the UserSchema is compiled directly in the mongoose object.
And now is the Question: I noticed that every model compiled in server.js and the connection to the db are available in every middleware that I use just requiring the mongoose module"... "Why does it work?"
So... if I have a middleware that needs to access to the db the only thing I have to do is to require the moongose module and retreive models I need simply calling:
var MY_MODEL = mongoose.model("NAME_OF_THE_MODEL_COMPILED_in_serve.js");
I think this is a good thing but I have no idea about the why it is working. I mean... I have read tons of Questions and Answers talking about the best way to obtain this result but I have never read about this way.
I have also read the documentation about Express.js ... but nothing.
Is it maybe related with the caching system of Express ?
Is it a safe way to share a database connection across the Express App?
Thanks in advance,
Luca
As server.js
is the main entry point of your application, that is the first place where node sees the mongoose
module required.
Any update to the mongoose
module instance is reflected in that particular instance.
For example, if you require mongoose
in your server.js
file and in your user.js
model file, you will only make changes to the same mongoose
object.
This is due to the way CommonJS modules are cached throughout an application.
If you would like to read more about the way modules are being cached, I recommend the following two sources:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With