MongoJS Node.js modules:"db is not undefined" - javascript

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.

Related

Requiring files in electron without babel

I'm trying to convert a web application into an electron app. I have multiple functions, in different files that I've imported into my main.js using a transpiler.
However, whenever I try do that in my electron app, I run into an issue with a module I'm using to move away from using php to access my database. Instead I'm using the mysql module on npm.
I want to save this function in its own file, and then require it in main.js. When I try to transpile it with babel, I get an error about Net.Connection not working (or something along those lines). As I understand it, this is because of how Node works. I'm happy to work around this, but I'm hoping there's a way to save this function in another file, and import it without having to use babel.
function loadColourFilter(){
var mysql = require('mysql');
let query_result;
var connection = mysql.createConnection({
host : 'xxxxxxxxxxxx',
user : 'xxxxxxxxxxxx',
password : 'xxxxxxxxxxxx',
database : 'xxxxxxxxxxxx'
});
connection.connect();
let query = "xxxxxxxxxxxxxxxx";
connection.query(query, function (error, results, fields) {
});
connection.end();
return (query_result);
}
EDIT: I've removed some parts of the function to keep credentials safe and whatnot. I'm fairly certain their absence won't change anything when trying to solve this.
EDIT:
My project directory is essentially
src
--- js
--- --- main.js
--- functionFile.js // This would be where my loadColourFilter function above would be saved
--- node_modules
--- --- ...
--- index.html // js/main.js is referenced in a script tag here.
--- main.js // Where the electron window is created.
--- package.json
There should be 2 js contexts, one running in the electron app and one running in node. You won't be able to require you scripts directly from your directory if you are in the electron context (which is like a browser js context).
I'm just assuming this is the case since we don't get a lot of information for your problem, and the other answer should have resolved your problem.
Try to include your js file in your index.html and see what's up.
Edit: Since it's a Transpiling error with babel, babel is probably transpiling for node when it should transpile for the browser.
You can easily make a simple local module using NodeJS by creating a source file and then adding a module.exports assignment to export some functionality/variables/etc from the file. In your case something like a file named colourFilter.js with the contents:
function load(){
var mysql = require('mysql');
let query_result;
var connection = mysql.createConnection({
host : 'xxxxxxxxxxxx',
user : 'xxxxxxxxxxxx',
password : 'xxxxxxxxxxxx',
database : 'xxxxxxxxxxxx'
});
connection.connect();
let query = "xxxxxxxxxxxxxxxx";
connection.query(query, function (error, results, fields) {
});
connection.end();
return (query_result);
}
module.exports = load
And then in your code where you'd like to use it include it by doing something like:
loadColourFilter = require('colourFilter.js')
And use the function like
let result = loadColourFilter()
This is a simple way to split up your code into multiple files/classes/modules but still keep one main file/class/module as the important one which is the public-facing portion or entry point. And of course you don't have to use the names I've used above :P
If you would like to make an object-style module you can instead export an object like
module.exports = {
load
}
Or
module.exports = {
load: loadFunctionNameInThisFile
}
And then use it like
const colourFilter = require('colourFilter.js')
let result = colourFilter.load()

Error in accessing JSON object in nodejs

I have a variable var sessions={} in file called 'UserSessions.js'. I am maintaining some information of each user in sessions={} with a unique timestamp. I have exported this variable to make it available to other files.
When I access the sessions={} in main file 'app.js' everything works fine.
But when I try to access same variable from another file 'Sessiongreet.js', it gives error.
Here is how I access the data :
Suppose '2017-04-07T11:55:40.162Z' is the unique timestamp assigned only once.
In app.js:
This Works fine:
const UserSessions=require('./UserSessions.js');
sessionId='2017-04-07T11:55:40.162Z';
var data=UserSessions.sessions[sessionId].context;
In sessionGreet.js:
This gives error:
const UserSessions=require('./UserSessions.js');
sessionId='2017-04-07T11:55:40.162Z';
var data=UserSessions.sessions[sessionId].context;
I know that UserSessions.sessions[sessionId].context exists as it is accessible in app.js file before accessing it in another file.
Here is the exact error what I get :
TypeError: Cannot read property '2017-04-07T11:55:40.162Z' of undefined
at initSession (/media/row_hammer/sessionGreet.js:24:33)
at Object.run (/media/row_hammer/sessionGreet.js:67:2)
at Object.handlePostback (/media/row_hammer/sessionTemp.js:89:19)
at runPostback (/media/row_hammer/app.js:113:15)
at /media/row_hammer/app.js:161:3
at Object.findOrCreateSession (/media/row_hammer/UserSessions.js:83:4)
at Bot.bot.on (/media/row_hammer/app.js:159:15)
at emitThree (events.js:116:13)
at Bot.emit (events.js:194:7)
at Bot._handleEvent (/media/row_hammer/node_modules/messenger-bot/index.js:254:10)
Also, In sessionGreet.js:
//EVEN this line shows 'undefined'
console.log(UserSessions.sessions);
Why am I getting this error even though flow of program is correct?
It may be that app.js and Sessiongreet.js are in different folders.
'./UserSessions.js' means that UserSessions.js is in the same folder as the file issuing the require().
If app.js is in the same folder as UserSessions.js, but Sessiongreet.js is in different folder, this would explain your issue.

NodeJs : TypeError: require(...) is not a function

I am trying to require a file and afterwards pass it to a var. I am following this tutorial to create an authentication system. After writing the server.js file and trying to compile I got a BSON error therefore I changed the line that required the release version of it in mongoose.
Here are my code and error:
server.js
require('./app/routes')(app, passport);
Error
require('./app/routes')(app, passport);
^
TypeError: require(...) is not a function
at Object.<anonymous> (d:\Node JS learning\WorkWarV2\server.js:38:24)
at Module._compile (module.js:434:26)
at Object.Module._extensions..js (module.js:452:10)
at Module.load (module.js:355:32)
at Function.Module._load (module.js:310:12)
at Function.Module.runMain (module.js:475:10)
at startup (node.js:117:18)
at node.js:951:3
Process finished with exit code 1
I have read that this usually means that requireJS is not getting loaded properly yet I am not aware why or how to fix it.
Edit due to comment:
As asked, here is the result of console.log(require);
For me, when I do Immediately invoked function, I need to put ; at the end of require().
Error:
const fs = require('fs')
(() => {
console.log('wow')
})()
Good:
const fs = require('fs');
(() => {
console.log('wow')
})()
I think this means that module.exports in your ./app/routes module is not assigned to be a function so therefore require('./app/routes') does not resolve to a function so therefore, you cannot call it as a function like this require('./app/routes')(app, passport).
Show us ./app/routes if you want us to comment further on that.
It should look something like this;
module.exports = function(app, passport) {
// code here
}
You are exporting a function that can then be called like require('./app/routes')(app, passport).
One other reason a similar error could occur is if you have a circular module dependency where module A is trying to require(B) and module B is trying to require(A). When this happens, it will be detected by the require() sub-system and one of them will come back as null and thus trying to call that as a function will not work. The fix in that case is to remove the circular dependency, usually by breaking common code into a third module that both can separately load though the specifics of fixing a circular dependency are unique for each situation.
For me, this was an issue with cyclic dependencies.
IOW, module A required module B, and module B required module A.
So in module B, require('./A') is an empty object rather than a function.
How to deal with cyclic dependencies in Node.js
Remember to export your routes.js.
In routes.js, write your routes and all your code in this function module:
exports = function(app, passport) {
/* write here your code */
}
For me, I got similar error when switched between branches - one used newer ("typescriptish") version of #google-cloud/datastore packages which returns object with Datastore constructor as one of properties of exported object and I switched to other branch for a task, an older datastore version was used there, which exports Datastore constructor "directly" as module.exports value. I got the error because node_modules still had newer modules used by branch I switched from.
I've faced to something like this too.
in your routes file , export the function as an object like this :
module.exports = {
hbd: handlebar
}
and in your app file , you can have access to the function by .hbd
and there is no ptoblem ....!
I don't know how but in may case it got fixed when I changed
require('./routes')(app)
to
require('./routes')
In my case i fix when i put the S in the module.exportS,
BEFORE:
module.export = () => {}
AFTER:
module.exports = () => {}

Check for node modules being loaded using jasmine-node

So I'm trying to teach myself Jasmine (for node) by working through a tutorial for a Mongoose project, TDD style, writing tests for what each step is supposed to accomplish, then following the actual tutorial, etc.
Of course, my first test is failing.
app.js at this point is two lines:
var mongoose = require('mongoose');
console.log(mongoose.version);
This runs fine. My test however, still fails:
var app = require('../src/app.js');
describe('App startup', function() {
it('loads mongoose', function() {
expect(app.mongoose.version).toBeDefined();
});
it('loads jasmine-jquery', function() {
expect($).toBeDefined();
});
});
Results in
Failures:
1) App startup loads mongoose
Message:
TypeError: Cannot read property 'version' of undefined
Stacktrace:
TypeError: Cannot read property 'version' of undefined
at null.<anonymous> (/home/jbhelfrich/mongooseBlog/spec/init.spec.js:5:36)
(The jquery test is, of course, expected to fail still at this point.) I've tried it with and without the 'app.' in the expect clause, but I get the same error--the test suite doesn't see the internals of app.js. But I know it's loading the app.js file correctly, because it's running it--the console.log output appears ahead of the test results.
So I suspect I've misunderstood something fundamental about scope, or some other rookie mistake, but I'm not sure what that is.
Node.js is structured into modules. If you want a a module's properties to be accessible, that module's properties must be defined in the module.exports variable. This is what an export might look like (note that exports references module.exports):
var mongoose = require('mongoose');
console.log(mongoose.version);
exports.mongoose = mongoose;
Then when you've used require() on a file with the code shown above, the variables will be set, where app is equivalent to module.exports in the module that is being loaded:
var app = require('../src/app.js');
console.log(app.mongoose.version);

MongoClient TypeError

I am a NodeJS newbie and JS can-kicker trying out DI for the first time. Here are the questions I looked at before deciding to ask mine, since they show the same error: [1][2]
Running my entry point yields:
this.client = new MongoClient(server);
^
TypeError: undefined is not a function
Entry point
var config = require('./config.json');
var Providers = require('./providers');
var providers = new Providers(config.db);
console.log(providers);
./providers/index.js
Both AssetProvider and UserProvider suffer the same error. I think I only need to show one.
module.exports = function Provider(dbConfig)
{
var UserProvider = require('./userProvider');
var AssetProvider = require('./assetProvider');
this.users = new UserProvider (dbConfig.name, dbConfig.host, dbConfig.port);
this.assets = new AssetProvider(dbConfig.name, dbConfig.host, dbConfig.port);
}
./providers/userProvider.js
Problem line marked
var mongodb = require('mongodb');
var MongoClient = mongodb.MongoClient;
var Server = mongodb.Server;
var ObjectID = mongodb.ObjectID;
var UserProvider = function (database, host, port) {
var server = new Server(host, port, { auto_reconnect: true });
// Error is here
this.client = new MongoClient(server);
this.client.open(function (error, client) {
this.db = client.db(database);
});
};
// ...a bunch of prototype stuff...
// ...
module.exports = UserProvider;
From what I have read in other locations online, I don't see anything wrong with my syntax. I have tried the following declaration...
function UserProvider(database, host, port)
as opposed to
var UserProvider = function(database, host, port)
Everything else I did was comparable to slapping a car engine with a wrench. The truth is, I simply do not understand what is so wrong here, but I do know that I just want to make a composition of objects across files so that my entry point can readily use all providers through a single object.
JohnnyHK turned out to be correct about it being a version issue.
Oddly enough, the error did not go away when running npm update mongodb
However, it did go away when I ran npm install mongodb a second time.
No changes were made in the code, and mongodb was already inside the local
node_modules folder. Even so, I suspect this had to do with a discrepancy between an instance in node_modules and an instance in NODE_PATH.
I'm only speculating as to why exactly npm install solved the problem considering the latest version should have been installed. All I know is that the error is gone and the code is working.
Thank you for the comments!
I got exactly the same issue. After a quick research I realised that I have an old mongodb module version (0.9.x). After installing the latest (1.13.19) - the issue has been fixed.
npm install mongodb#1.3.13

Categories

Resources