I'm new to Node.js, MongoDB and MongoJS.
I have app.js
which is the server I run from my command line with node app.js
. On a local machine with OS X 10.9.1 with Node.js v0.10.28.
In app.js
I have (as snippets)
var db = require('./database');
var blog = require('./classes/blog');
and database.js
has
var db = require("mongojs");
db.connect('mydb', ["Users", "Posts"]);
and /classes/blog.js
has
function load(OnDone) {
if (db.connected) {
OnDone();
}
}
When I call blog.load()
I get
ReferenceError: db is not defined
at Object.load (node/classes/blog.js:13:6)
at node/app.js:36:7
at Server.onRequest (node/server.js:35:12)
at Server.EventEmitter.emit (events.js:98:17)
at HTTPParser.parser.onIncoming (http.js:2108:12)
at HTTPParser.parserOnHeadersComplete [as onHeadersComplete] (http.js:121:23)
at Socket.socket.ondata (http.js:1966:22)
at TCP.onread (net.js:527:27)
Everything in my app works as expected except when I try to call my load()
function which uses the db
var that I thought I declared in app.js
.
Why would db
be undefined? Am I using modules wrong?
Note: if you can't tell, I extracted these lines of codes from my scripts since my app so far is relatively long for a SO question and I don't want to show it all unless I need to.
I believe Node.js modules are contained so do not have access to variables defined in their parents (as I assumed).
I moved db
to the global namespace (I removed var
) and it's working now.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.