简体   繁体   English

app.js中定义的变量是否可以通过Express和node js中的路由功能访问?

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

I was coding using express js, and I noticed that I declared this in app.js 我正在使用Express JS进行编码,我注意到我在app.js中声明了这一点

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

Then in my /models/userSchema.js 然后在我的/models/userSchema.js中

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

However in my routes/upload.js 但是在我的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" //这知道我正在访问名为“ 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. 我不确定为什么这样工作,就像在upload.js和userSchema.js中执行的代码如何知道我正在使用的数据库是testdb。 Isn't this declaration of var mongoose = require('mongoose'); 声明不是var mongoose = require('mongoose'); creates a new object separate from the one in app.js? 创建一个与app.js中的对象分开的新对象?

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. 虽然有一些方法可以传递我的应用程序对象,但我可以通过这些模块。

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. 在node.js中,加载了require模块被缓存,以便在两个不同的文件中调用require('mongoose')返回mongoose模块的相同实例。

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. 因此,虽然一个文件中的变量不能在其他文件中直接访问,但是同一模块内的变量在require该模块的文件之间有效地共享。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM