Are the variables defined in app.js accessible to the functions in routes, in Express and node js?

StackOverflow https://stackoverflow.com/questions/23686872

Frage

I was coding using express js, and I noticed that I declared this in app.js

  var mongoose = require ('mongoose'); 
  var db =mongoose.connect('mongodb://localhost/testdb');

Then in my /models/userSchema.js

 var mongoose = require('mongoose');
 var users = mongoose.model('users',UserSchema);
 module.exports = users;

However in my routes/upload.js

var mongoose = require ('mongoose');
var db =mongoose.connect('mongodb://localhost/testdb');`
//some code

mongoose.model('users').find(); 

// This knows that i am accessing the database called "testdb"

I am not sure why this works like how the code executing in upload.js and userSchema.js knows that the database i am using is testdb. Isn't this declaration of var mongoose = require('mongoose'); creates a new object separate from the one in app.js?

War es hilfreich?

Lösung

In node.js, modules loaded with require are cached so that calling require('mongoose') in two different files returns the same instance of the mongoose module.

So while variables from one file are not directly accessible in other files, variables within the same module are effectively shared between the files that require that module.

Andere Tipps

Mongoose is singleton. That is when you require it again you get the instance you first initialized.

App level variables are not visible in other modules. There are ways to pass the app object I tide modules though.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top