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

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

Domanda

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?

È stato utile?

Soluzione

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.

Altri suggerimenti

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.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top