I have node app pointing at a mongodb using the connection string:
var url = "mongodb://localhost:27017/";
This variable is used throughout my code:
//When a connection to server is made from client
io.on('connection', (socket) => {
//When host connects for the first time
socket.on('host-join', (data) =>{
//Check to see if id passed in url corresponds to id of game in database
MongoClient.connect(url, function(err, db) {
if (err) throw err;
var dbo = db.db("agile_poker");
var query = { id: parseInt(data.id)};
dbo.collection('sessions').find(query).toArray(function(err, result){
if(err) throw err;
//A game was found with the id passed in url
if(result[0] !== undefined){
var gamePin = Math.floor(Math.random()*90000) + 10000; //new pin for game
games.addGame(gamePin, socket.id, false, {playersAnswered: 0, questionLive: false, gameid: data.id, question: 1}); //Creates a game with pin and host id
var game = games.getGame(socket.id); //Gets the game data
socket.join(game.pin);//The host is joining a room based on the pin
console.log('Game Created with pin:', game.pin);
//Sending game pin to host so they can display it for players to join
socket.emit('showGamePin', {
pin: game.pin
});
}else{
socket.emit('noGameFound');
}
db.close();
});
});
});
Its been a year since I last ran this locally, but now when I start the app on port 3000, and I type in localhost:3000 or 192.168.0.1:3000 the app doesn't load and instead shows connection refused.
I saw that making HTTP calls to mongodb was deprecated (when I try to hit the mongodb port directly through a browser), but would that cause me the issue I'm experiencing with running my app locally?
Related
I'm trying to build a real time web page and use postgreSQL as my database. I use node.js and express to build backend stuff. Since this is a real time webpage and needs to update information very frequently, I keep a long connection with postgreSQL, which looks like:
app.get('/:A/:B', function(req,res){
var A = req.params.A;
var B = req.params.B;
var client = new pg.Client(config[A][B]);
client.connect(function(err){
if (err) {
console.log("Error occurred when try to connect the database",err);
}
else {
console.log("Connected to the database");
}
});
Do some queries with current database connection...
}
The problem is, when I change the value of A and B in browser and try to connect to a new database, I didn't disconnect with the old one so the info on my page are still from the old database. I'm new to node and web development. Can anyone let me know how to disconnect with the old database when client try to go to a new url?
I think is not good way to create connection for each request. If size of A-B variants is limited then create of connection pool on start is better.
app.get('/:A/:B', function(req, res, next){ // next to forwarding error
var A = req.params.A;
var B = req.params.B;
var client = new pg.Client(config[A][B]);
client.connect(function(err){
if (err)
return next(err); // go to error-middleware
console.log("Connected to the database");
// Do some queries with current database connection...
// Keep it mind that they're also asynchronous, so better way is use promises or async (https://github.com/caolan/async)
client.end(function (err) {
if (err)
next(err);
});
});
}
// Error middleware
app.use(function(err, req, res, next) {
console.log(req.url, err.message);
})
The basic idea of the following code is I read messages off an ActiveMQ Artemis installation and insert them into a MongoDB instance.
It works well for up to a hundred or so messages per second but crashes if I throw a few thousand at it. My first guess would be the constant opening and closing of database connections. Should I also think about using an in-memory store and doing bulk database inserts?
The code is all running in node using the mqtt and mongodb npm packages. The code below, the database and the queue are all running in docker containers if it makes any difference.
var mqtt = require('mqtt'),
client = mqtt.connect('mqtt://mq:1883', {
username: "*************",
password: "*************"
}),
MongoClient = require('mongodb').MongoClient,
ObjectId = require('mongodb').ObjectID,
assert = require('assert'),
url = 'mongodb://db:27017/uo-readings';
client.on('connect', function () {
client.subscribe('readings');
});
client.on('error', function(error){
console.log(error)
});
client.on('message', function (topic, message) {
console.log(message.toString());
MongoClient.connect(url, function(err, db) {
assert.equal(null, err);
console.log("Connected correctly to server.");
db.collection('readings').insertOne(JSON.parse(message.toString()), function(err, result) {
assert.equal(err, null);
console.log("Inserted a document into the readings collection.");
});
client.end(function(){
console.log("Closing Connection.");
db.close();
});
});
});
See #Jonathan Muller's comment above
I'm setting up a simple chat server with NodeJS that only uses a server and client. It works, and I can open up multiple client windows on the same machine, but now I need a bit more.
I would like to:
Give each client the option to set usernames
Have a client request current time from server
Action commands like "/me punches the warlock" that the server shows others as "User punches the warlock"
This sounds like a quick days work, but I just started looking at UDP and I can't quite find any examples online other than a generic server/client thing that sends and gets messages. How would I go about those tasks?
Code:
Server.js:
var dgram = require('dgram'); //import datagram to get everything needed for UDP
var PORT = 22222;
var CLIENT_PORT = 2223;
// An IP address that's reserved on each network
// Gets sent to the server
var ADDRESS = "-"; //dont want to show my IP :)
var sock = dgram.createSocket({reuseAddr: true, type: 'udp4'}); //can now open multiple clients
var current_time = Date.now(); //?
function sendMessage(data) {
sock.send(data, 0, data.length, PORT, ADDRESS, function(err){
if(err){
throw err;
}
});
}
sock.on("message", function(data, rinfo) {
//listen for messages and print them
console.log(data);
//Check if the client's port was equal to the port to find client data on
//If so, get packet
if (rinfo.port === CLIENT_PORT) {
console.log('\nreceived');
//call function to broadcast the data out to everyone on the local network
sendMessage(data);
}
//Get the string data from the data buffer.
var stringData = data.toString(); //also could be toJSON()
console.log(stringData);
//Convert that string back into a buffer by making a new Buffer and passing it in.
//The buffer class can take a string, an array or just a number of bytes to allocate to memory
var backToBuffer = new Buffer(stringData); //can take a string, array or just a size to allocate
console.log(backToBuffer);
});
//This opens the connection and starts listening
//(Client Port, Address to listen to which is ALL, What to do)
sock.bind(CLIENT_PORT, '', function(){
sock.setBroadcast(true);
console.log('listening on port ' + PORT + "\n");
});
Client.js:
var dgram = require('dgram');
var SERVER_PORT = 22222;
var PORT = 22223;
var ADDRESS = "-";
//read input from the command line
var stdin = process.stdin;
var stdout = process.stdout;
var sock = dgram.createSocket({reuseAddr: true, type: 'udp4'});
var server_sock = dgram.createSocket({reuseAddr: true, type: 'udp4'});
function sendMessage(data) {
//onsole.log("sending data");
sock.send(data, 0, data.length, PORT, ADDRESS, function(err) {
if(err) {
throw err;
}
//nsole.log("sent");
});
}
server_sock.on("message", function(data, rinfo) {
console.log("received " + data.toString());
});
server_sock.bind(SERVER_PORT, '', function() {
console.log('listening to server port');
});
sock.bind(PORT, '', function() {
sock.setBroadcast(true);
console.log("please enter a message\n");
stdin.resume();
stdin.on("data", function(data) {
sendMessage(data);
});
});
Node.js has loads of libraries to make realtime communication chats, I don't understand the choice of using UDP and managing everything by yourself, and it also looks that you are not very expert on this. My suggestion is to use a websocket library like it can be socket.io which they even have an example of a simple chat in their website http://socket.io/get-started/chat/
Using socket.io (or similar) it will help you a lot since it has sessions so you can save the username and return it everytime you post a message.
Below I wrote a small example of the server side (took from the index.js of the get-started above).
io.on('connection', function(socket){
var username = 'RANDOM';
socket.on('chat message', function(msg){
//here you should catch messages starting with "/" and parse them to write a different message
io.emit('chat message', username + ': ' msg);
});
socket.on('update username', function(msg) {
username = msg;
io.emit('username changed', username);
});
});
I hope it helps.
I'm attempting to deploy a very simple app to Heroku. The code for the application can be found on Ray Wenderlich's site, here: http://www.raywenderlich.com/61078/write-simple-node-jsmongodb-web-service-ios-app I keep getting the same error whenever I try to have Heroku compile the code...
var mongoHost = "mongodb://username:password#ds041140.mongolab.com:41140/heroku_app23491233";
var mongoPort = 41140;
var collectionDriver;
var mongoClient = new MongoClient(new Server(mongoHost, mongoPort)); //B
mongoClient.open(function(err, mongoClient) { //C
if (!mongoClient) {
console.error("Error! Exiting... Must start MongoDB first");
process.exit(1); //D
}
var db = mongoClient.db("heroku_app23491233"); // E
collectionDriver = new CollectionDriver(db); //F
});
When I type heroku logs, the error I get comes from if (!mongoClient) above...
app[web.1]: Error! Exiting... Must start MongoDB first
I'm sure the problem lies somewhere in my attempt to connect to the MongoLab database. I've copied the URI from MongoLab and I've created a user with the proper credentials.
I can connect to localhost just fine with very similar code, so I'm not sure what is going wrong in this example.
Thank you.
Based on the docs, my best guess is that it's because the Server constructor expects the first argument to contain only the host name (in the case of your MongoLab, ds041140.mongolab.com). However, I think you can pass your connection string into MongoClient.connect:
// Make sure to replace username and password with the proper values.
var mongoHost = "mongodb://username:password#ds041140.mongolab.com:41140/heroku_app23491233";
MongoClient.connect(mongoHost, function(err, db) {
if (err) return console.log(err);
db.collection('mongoclient_test').update({a:1}, {b:1}, {upsert:true}, function(err, result) {
db.close();
if (err) return console.log(err);
console.log('Okay', result);
});
});
Documentation Page For MongoClient
Hopefully that helps!
I've been looking for a way to do various operations on a mongo database, depending on which route a user connects to on my website. So doing a html-post to www.mysite.com/data would add info to a mongo DB, and doing a html-get at the same url would get data from the same database. I managed to solve that, but everytime I turn on my server with the website I get 5 connections registred at the mongo database. Why is this, and is it bad?
My code:
I'm runing this code in mongo.js:
var mongodb = require('mongodb');
module.exports.init = function (callback) {
var server = new mongodb.Server("127.0.0.1", 27017, {});
new mongodb.Db('test', server, {w: 1}).open(function (error, client) {
//export the client and maybe some collections as a shortcut
module.exports.client = client;
module.exports.myCollection = new mongodb.Collection(client, 'myCollection');
callback(error);
});
};
I initialize everything running (app.js):
/express set-up/
var mongo = require('./mongo.js');
/.../
mongo.init(function (error) {
if (error)
throw error;
app.listen(3000, function(){
console.log("Express server listening on port %d in %s mode",3000,
app.settings.env);
});
});
And, for example, the post looks like (still app.js):
app.post('/App', function(req, res) {
users = users.concat(req.body);
res.redirect('/App');
//Add user to MongoDB
mongo.myCollection.insert({name: req.body.name, car: req.body.car, website: req.body.website, phone: req.body.phone}, {safe:true}, function(err, objects) {
if (err)
console.warn(err.message);
});
Pretty sure my redirect isn't working as I want it too here, but that's another issue.
Anny suggestions on why I get five connects every time I start the server?
The five connections are because that is the default poolSize (5). You can adjust it, as outlined in the server options docs - it also mentions the default.