node.js / mongodb file structure - node.js

I'm trying to set up this simnple NodeJS/mongodb app and I have my files structured like this:
server.js
|
+-routes/menu.js
+-routes/cases.js
In my server.js I declare my mongodb vars like this:
var express = require('express'),
mongo = require('mongodb'),
Server = mongo.Server,
MongoClient = mongo.MongoClient,
Db = mongo.Db,
http = require('http'),
app = express(),
httpServer = http.createServer(app),
bodyParser = require('body-parser'),
server = new Server('host.mongohq.com', 10066, {auto_reconnect : true}),
db = new Db('myDb', server);
db.open(function(err, client) {
client.authenticate('myUser', 'myPassword', function(err, success) {
console.log('Authenticated');
});
});
var cases = require('./routes/cases'),
menu = require('./routes/menu');
But then when I try to reference my db var in eg menu.js like this:
db.collection(myCollection, function(err, collection) {});
I get an error that db is not defined.
Obviously I can move all the mongodb declarations down to both my menu.js and cases.js file but that's just very elegant. So how do I create one mongodb instance var and refer to it from my included files?
Thanks in advance...

You need to require server.js in your menu.js file.
Your db object isn't global. If you want it to be, declare it without var.

Related

Express issue - adding app.use(express.static('public')); to service static files negates MySQL pool functions - heroku related?

I really don't understand why this is occuring. I can create pool connections no problem without the use of app.use(express'static('public')); - the results show up in the Heroku console.
However, when I include this line to serve static files - nothing occurs in console. I am using Heroku - is it possible that this may be part of the issue? Or is this something obvious about Express that I'm missing?
var express = require('express');
var app = express();
var fs = require('fs');
var path = require('path');
var mysql = require('mysql');
var pool = mysql.createPool({
connectionLimit: 10,
host:'*******',
user:'*******',
password:'*******',
database:'*******'
});
app.use(express.static('public'));
app.get('/',function(req,res){
pool.query("*********", function(err, rows, fields) {
if (err) throw err;
console.log(rows[0]);
});
});
app.listen(process.env.PORT || 3000);
Project is stored as public/index.html with files in sub-directories.

app is undefined in loopback custom js file

i am using nodejs loopback framework.i want to run a cron job.i created a custom js file for this cron job in server/boot folder.but when manually i run this file(xyz). app is undefined.my code is below
var app = require('../server.js');
console.log(">>>>>>>>>>>>>>in test")
var subscription = app.models.UserNotification;
console.log(">>>>>>>>>>>..in manage")
var datasource=subscription.dataSource;
var query="SELECT DISTINCT userId FROM users_subscription";
datasource.connector.query(sql,function (err, data) {
console.log(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>data is>>>>>",data);
})
here is my server.js file
var bodyParser = require('body-parser');
var loopback = require('loopback');
var boot = require('loopback-boot');
var app = module.exports = loopback();
var passport = require('passport');
var bodyParser = require('body-parser').urlencoded({
extended: true
})
app.use(bodyParser)
app.use(loopback.context());
app.use(loopback.token());
var path = require("path");
var url = require('url');
var http = require('http');
var fs = require('fs');
var request = require('request');
app.start = function() {
// start the web server
return app.listen(function() {
app.emit('started');
var baseUrl = app.get('url').replace(/\/$/, '');
console.log('Web server listening at: %s', baseUrl);
if (app.get('loopback-component-explorer')) {
var explorerPath = app.get('loopback-component-explorer').mountPath;
console.log('Browse your REST API at %s%s', baseUrl, explorerPath);
}
});
};
app.use(loopback.static(path.resolve(__dirname, '../client')));
app.use(loopback.static(path.resolve(__dirname, '../admin')));
app.use(loopback.static(path.resolve(__dirname, '../other-dir')));
boot(app, __dirname, function(err) {
if (err) throw err;
if (require.main === module) app.start();
});
Thanks,
It's really impossible to say for sure since you don't include the code that is included with:
var app = require('../server');
(which would be the most important code to include if the require returns undefined) but if app is undefined then it means that the module is loaded but its module.exports is undefined.
Do you export anything from that module?
Are you sure that it is really app that is undefined and not, say, app.models?
Without knowing the code in question those are the most reasonable things to investigate.
Update
If you don't export anything from your server.js (which was my suspection in my answer above, but now you confirmed it with you code and comment) then after this line:
var app = require('../server.js');
you will not be able to use app.models.UserNotification
If you want to use app.models in the code that requires server.js, then you'll have to add:
module.exports.models = SOMETHING;
in your server.js code. You don't seem to have anything called models in server.js, you don't export anything as module.exports.models, so you can't expect app.models to be defined in your code that does:
var app = require('../server.js');

Authentication failing connecting node.js with PostgreSQL

I have some of a database set up with PostgreSQL, and I am able to do everything I need from the psql REPL sort of thing, but when I try to access this though node.js on the same machine I get an password authentication filed for user"[my user name]" error.
As per an online tutorial, my database acces code is something like this:
var pg = require('pg');
var path = require('path');
var connectionString = require(path.join(__dirname, '../', '../', 'config'));
var client = new pg.Client(connectionString);
client.connect();
var query = client.query('CREATE TABLE items(id SERIAL PRIMARY KEY, text VARCHAR(40) not null, complete BOOLEAN)');
query.on('end', function() { client.end(); });
But as I already have the tables set up with some of my own functions, I'm simply trying to access those functions on POSTs, with:
var express = require('express');
var router = express.Router();
var pg = require('pg');
var path = require('path');
var connectionString = 'postgres://localhost:5432/[My User Name]?ssl=true;
router.post('/locations', function(req,res) {
var client = new pg.Client(connectionString);
client.connect();
var query = client.query([Call to my function, works in REPL, something like "SELECT * FROM create_location([Data from req])"]);
});
I have my pg_.conf set up as:
local all postgres peer
local all all trust
local all all 127.0.0.1/32 trust
host all all ::1/128 md5
your connectionstring seems to be wrong. a connection string has to be like:
postgres://[username]:[password]#[host]:[port]/[databasename]
and in your case:
postgres://[username]#localhost:5432/[databasename]?ssl=true

Separating modules in NodeJS for use with a single object

I have a NodeJS + ExpressJS + Socket.IO server and I am trying to divide my different namespaces into different modules.
Essentially I want to require the socket.io library in server.js, but have access to the io variable from my modules like this:
server.js
var app = require('express')();
var jwt = require('jsonwebtoken');
var server = require('http').Server(app);
var fs = require('fs');
var io = require('socket.io')(server);
var bodyParser = require('body-parser');
var _log = require('./logging/loggly.js').Client();
// Global NS
var SK = {
Namespaces:{}
};
var Migrations = require('./sockets/migrations');
var Backups = require('./sockets/backups');
var Cloudmanager = require('./sockets/cloudmanager');
SK.Namespaces[Migrations.NS] = Migrations;
SK.Namespaces[Backups.NS] = Backups;
SK.Namespaces[Cloudmanager.NS] = Cloudmanager;
....
....
migrations.js
var exports = module.exports = {};
///////////////////////////////////////////////
//
// Migrations Namespace
//
///////////////////////////////////////////////
exports.NS = 'migrations';
exports.socket = io.of('/'+exports.NS); // PROBLEM IS 'io' IS UNDEFINED HERE
exports.socket.on('connection', function(socket){
});
I have basically the same code in all 3 of my socket.io namespaces, but I don't have access to the io variable that is used in server.js. Is there a way to have access here? Do I just use a require()? Whats the best way to achieve this functionality?
Thank you
You can export a function from migrations.js that accepts the io value as a parameter:
module.exports = function (io) {
var socket = io.of('/'+exports.NS);
socket.on('connection', function(socket){});
return {
NS: 'migrations',
socket: socket,
};
};
Then simply require and invoke this function in your server.js:
var Migrations = require('./sockets/migrations')(io);

Mongodb in node.js

I'm trying to get my app to return something from the mongodb server its connected to but every time it returns :
{col :
{manager:
{driver:[object],
helper:[object],
.
.
.
query{}}
in my app.js i wrote :
var mongo = require('mongodb');
var monk = require('monk');
var db = monk('localhost:27017/Messages');
var collection = db.get('msgCollection');
var a= collection.find({});
console.log(a);
I checked and the database and collection exist. If i write in the mongo console db.msgCollection.find() it works
Any one knows what the problem ?
Thank you!
Monk's API is asynchronous (as is most of nodejs api).
To get results from query, You have to:
var mongo = require('mongodb');
var monk = require('monk');
var db = monk('localhost:27017/Messages');
var collection = db.get('msgCollection');
collection.find({}, function(err, data) {
//handle error
console.log(data);
});
Or use promises.

Resources