Setting up a MongoDB database connection with node.js - javascript

How would I set up a MongoDB database connection with node.js?
Here is my app.js file:
var express = require('express'),
app = express(),
server = require('http').createServer(app),
io = require('socket.io').listen(server);
server.listen(3000);
app.get('/', function(req, res) {
res.sendfile(__dirname + '/index.htm');
});
app.use(express.static(__dirname + '/assets'));
io.sockets.on('connection', function(socket) {
socket.on('send message', function(data) {
io.sockets.emit('new message', data);
});
});
I have already set-up MongoDB and have it running as a service on Windows.

As of 1.2, the recommended way to perform a connection is in documentation:
http://mongodb.github.io/node-mongodb-native/driver-articles/mongoclient.html
excerpt:
var MongoClient = require('mongodb').MongoClient
, Server = require('mongodb').Server;
var mongoClient = new MongoClient(new Server('localhost', 27017));
mongoClient.open(function(err, mongoClient) {
var db1 = mongoClient.db("mydb");
mongoClient.close();
});
You may find that a connection singleton is useful for the current state of the official node.js driver. Below is some sample code that I use:
connection.js module:
var MongoClient = require('mongodb').MongoClient;
var db_singleton = null;
var getConnection= function getConnection(callback)
{
if (db_singleton)
{
callback(null,db_singleton);
}
else
{
//placeholder: modify this-should come from a configuration source
var connURL = "mongodb://localhost:27017/test";
MongoClient.connect(connURL,function(err,db){
if(err)
log("Error creating new connection "+err);
else
{
db_singleton=db;
log("created new connection");
}
callback(err,db_singleton);
return;
});
}
}
module.exports = getConnection;
Referencing module:
var getConnection = require('yourpath/connection.js')
function yourfunction()
{
getConnection(function(err,db)
{
//your callback code
}
.
.
.
}

Related

Value not updating in PostgreSQL using NodeJs

var express = require('express');
var app = express();
var pg = require('pg');
var connectionString = "postgresql://postgres:sujay123#localhost:3001/redc";
app.use(express.static('public'));
app.get('/index.html', function (req, res) {
res.sendFile( __dirname + "/" + "index.html" );
})
app.get('/process_get', function (req, res) {
response = {
name:req.query.name,
lat:req.query.lat,
long1:req.query.long
};
console.log(response);
res.end(JSON.stringify(response));
var client = new pg.Client(connectionString);
client.connect();
console.log("connect");
console.log("INSERT INTO data(name, latitude,longitude) values('"+req.query.name+"',"+req.query.lat+","+req.query.long+")");
var i = client.query("INSERT INTO data values('"+req.query.name+"',"+req.query.lat+","+req.query.long+")");
console.log(i);
console.log("Query Inserted")
})
var server = app.listen(3001, function () {
var host = server.address().address
var port = server.address().port
console.log("Example app listening at http://%s:%s", host, port)
})
I am getting this code and running but when i check the db the insert query has not worked and th values in the 3 paramters are coming of name, lat and long just the query isnt working i guess.
Yes your syntax for insert is wrong. The query that you are logging in console looks correct, but it's different from the string you're using in the database query.

node mssql throws error: pool is draining and cannot accept work

I have a node js app with the npm mssql module. I have purchased a cloud Windows 2012 server and when trying to call the stored procedure, it throws the error.
Throws error at ps.prepare("exec usp_Get_Cars #param", function(err)
var express = require('express');
var app = express();
var router = express.Router();
var util = require('util');
var recieve = require('./recieve');
var userID = "7DF506E1-700D-4D30-8162-74A903743561";
app.use('/node_modules', express.static(__dirname + '/node_modules'));
app.use('/style', express.static(__dirname + '/style'));
app.use('/script', express.static(__dirname + '/script'));
var sql = require('mssql');
var config = {
user: 'prod_admin',
password: 'myPassword',
server: 'serverName',
database: 'elements'
};
app.get("/getCars/:userID", function(req, res) {
var userID = req.params.userID;
var connection = new sql.Connection(config, function(err) {
var ps = new sql.PreparedStatement(connection);
ps.input('param', sql.NVarChar(sql.MAX));
ps.prepare("exec usp_Get_Cars #param", function(err) {
ps.execute({
param: userID
}, function(err, recordset) {
console.log('Recordset: ' + JSON.stringify(recordset));
res.send(recordset);
ps.unprepare(function(err) {
console.log('Error on unprepare: ' + err);
});
});
});
});
});
app.get('/', function(req, res) {
res.sendFile('home.html', {
'root': __dirname + '/templates'
});
});
app.listen(3000, function() {
console.log('Node server running # http://localhost:3000');
});
I did try searching for why this error occurs, but can't find anything relating to mssql or node. You can see the code that throws the error here. I am wondering if this is an issue with the server setup?
There are no errors in the js file and I have no issues running this on my Windows 10 local machine. Any ideas?
It was a firewall issue with AWS. I was unable to determine how to fix it through Amazon. But I moved my database to another server and it worked.

How to subscribe client and save the data to MongoDB in Node.js, Mosca and MQTT

I have a remote device which is nothing but a sensor. It will continuously give me some numbers. Actually I am receiving those numbers in my node.js server, I do not want to publish those data. I want to subscribe my client and want to print my topic and message after client subscribed. Here is my Node.js server and mqtt in c. Run both files using node app.js and gcc main.c after ./a.out.
How can I resolve this problem?
Files are shown below:
app.js
'use strict';
//dependencies
var express = require('express'),
passport = require('passport'),
strategy = require('passport-local').Strategy,
mongoose = require('mongoose'),
mongodb = require('mongodb'),
bodyParser = require('body-parser'),
path = require('path'),
acl = require('acl'),
mosca = require('mosca');
exports.init = function(pp) {
passport = pp;
app = pp;
return exports;
};
exports.root = function(req, res) {
// Running
res.send("Running");
};
//create express app
var app = express();
app.appname ="watersensor_DB";
//config mongoose
mongoose.Promise = global.Promise;
app.db = mongoose.createConnection('localhost/'+app.appname);
app.db.on('error', console.error.bind(console, 'mongoose connection error: '));
app.db.once('open', function () {
// Store All Data
});
//config mongodb
mongodb.connect("mongodb://localhost/"+app.appname, function(error, mdb) {
app.acl=new acl(new acl.mongodbBackend(mdb, app.appname));
});
//config data models
require('./models')(app, mongoose);
//Serve Frontend
app.use(express.static(path.join(__dirname, '/public/')));
//config Routes
var router = express.Router();
require('./routes')(app, router, passport);
//config express
app.set('secret','thisshouldnotbeinplaintext');
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.use(passport.initialize());
app.use(router);
//config mosca
var ascoltatore = {
//using ascoltatore
type: 'mongo',
url: 'mongodb://localhost:27017/mqtt',
pubsubCollection: 'ascoltatori',
mongo: {}
};
var settings = {
port: 1883,
backend: ascoltatore,
persistence: {
factory: mosca.persistence.Mongo,
url: 'mongodb://localhost:27017/mqtt'
}
};
var server = new mosca.Server(settings);
server.on('clientConnected', function(client) {
console.log('client connected', client.id);
});
// fired when a message is received
server.on('published', function(packet, client) {
console.log('Published', packet.payload);
});
server.on('ready', setup);
// fired when the mqtt server is ready
function setup() {
console.log('Mosca server is up and running');
}
//Port Listening
app.listen(7000, function(){
//Running
console.log("Node.js Server Is Running On localhost:7000");
});
main.c
#include <stdio.h>
main()
{
char buf[1024];
int i;
//mosquitto_sub -t 'test/topic' -v
//mosqui<to_pub -t 'test/topic' -m 'hello'
for(i=0; ;i++) {
//sprintf(buf, "mosquitto_pub -h 192.168.43.82 -p 1883 -t 'test' -m '%d'",i);
sprintf(buf, "mosquitto_pub -t 'test' -m '%d'",i);
printf("%s\n",buf);
system(buf);
sleep(1);
}
}
What you mean is that the node.js server get the data published from your remote device? After it, server store the data in MongoDB???
For this meaning, server do not need to subscribe the client. It can get the data from the below code.
server.on('published', function(packet, client) {
console.log('Published : ', packet.topic + " --- " + packet.payload);
var MongoClient = require('mongodb').MongoClient;
var url = "mongodb://localhost:27017/mydb";
MongoClient.connect(url, function(err, db) {
if (err) throw err;
var stringBuf = packet.payload.toString('utf-8');
var myobj3 = JSON.parse(stringBuf);
db.collection("customers").insertOne(myobj3, function(err, res) {
if (err) throw err;
console.log("1 record inserted");
db.close();
});
});
});

Triggering socket.io real-time notifications from Express 4 middleware

I am building a real-time notification system using socket.io. This is my server-side code at the moment:
bin/www:
var app = require('../app');
var server = http.createServer(app);
var io = app.io
io.attach(server);
server.listen(port, function(err) {
if (err) console.log(err);
console.log('Listening on port ' + port + '...');
});
app.js:
var socket_io = require('socket.io');
var express = require('express');
var app = express();
var io = socket_io();
app.io = io;
require('./config/socket')(app.io);
config/socket.js:
var User = require('../controllers/user');
module.exports = function (io) {
io.on('connection', function (socket) {
console.log('Socket.io connected');
socket.emit('connection', "Connection created.");
socket.on('send notification', function(data) {
User.createNotification(socket.request.user, data);
});
});
};
routes/index.js:
var express = require('express');
var User = require('../controllers/user');
var router = express.Router();
router.post('/order', User.order);
module.exports = router;
controllers/user.js:
var User = require('../models/user').model;
var io = require('socket.io');
module.exports = {
order: function(req, res) {
/* some create order code */
io.emit('send notification', 'Your order was successful!');
res.sendStatus(200);
}
}
I keep getting the error TypeError: io.emit is not a function whenever I try to call the route POST /send even though I am clearly initiating socket.io in my app.js and bin/www files and requiring it in controllers/user.js. All the examples I've seen online emit notifications from within this part:
io.on('connection', function (socket) {
socket.emit(event, msg);
});
but I want my notifications to be triggered from the middleware so I can send custom notifications to the user when certain events happen in the application backend.
Try the following instead:
io.on('connection', function(socket){
socket.on('xxx', function(obj){
io.emit('xxx', {xxx: xxx})
})
})
This should suppress your TypeError:.

Socket.io socket emit not being called

I have this index.js file on the client:
var socket;
var init = function() {
// Setup Socket:
socket = io.connect();
// Setup Event Handlers:
setEventHandlers();
// Connect to Server:
socket.emit('connect', {
name : "User Name"
});
console.log("Client Init Complete.");
}
var setEventHandlers = function() {
// Set Routes For Connections
socket.on("connection resp", onConnected);
}
var onConnected = function(data) {
console.log(data.resp);
}
And I have this code on the server:
// SETUP:
var express = require('express');
var app = express();
var http = require('http').Server(app);
var request = require('request');
var path = require('path');
var socket = require('socket.io')(http);
var server_port = process.env.OPENSHIFT_NODEJS_PORT || 8080;
var server_ip_address = process.env.OPENSHIFT_NODEJS_IP || '0.0.0.0';
var bodyParser = require('body-parser')
var fs = require('fs');
// SETUP:
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
extended : false
}));
app.configure(function() {
app.use(express.static(path.join(__dirname, 'public')));
})
var setEventHandlers = function() {
socket.sockets.on("connection", onInit);
};
var onInit = function(client) {
client.on("connect", onConnect);
};
var onConnect = function(data) {
console.log("Called");
}
// Send index page html
app.get('/', function(req, res) {
res.sendfile("public/html/index.html");
});
// Turn on server
http.listen(server_port, server_ip_address, function() {
console.log("App Listening on " + server_ip_address + ", server_port "
+ server_port);
});
setEventHandlers();
The issue is that on the onConnect on the server is never called. Eventhough I call socket.emit("connect") on the client.
After further testing, it seems that the socket id is undefined: this.id returns undefined.
You need to add quotes to the parameters in the socket.emit function like this:
// Connect to Server:
socket.emit('connect', {
'name' : 'User Name'
});
You should initialize your socket variable through io.connect("server address") and has i see in your code you have not passed any parameter to io.connect
.If server is in your local machine then connect to it by io.connect("http://localhost").
For more information see Docs. socket.io-client

Categories

Resources