MongoDB connections on Windows 2008 r2 error: getaddrinfo ENOTFOUND - node.js

I am writing a MEAN application for work and I have come up to a roadblock. My index.js file, which contains my mongo db connection information, seems to be wrong and I am scratching my head to find the solution. Unfortunately all similar issues I see are on the 'nix side. I am not very well versed in Windows so if this is a stupid question, I apologize.
Current index.js file:
var express = require('express');
var mongoose = require('mongoose');
var bodyParser = require('body-parser');
var methodOverride = require('method-override');
var _ = require('lodash');
var dbURI = 'mongodb:127.0.0.1\d$\db\pclistapp';
// Create the app
var app = express();
// Add middleware necessayr for the REST API
app.use(bodyParser.urlencoded({extended: true}));
app.use(bodyParser.json());
app.use(methodOverride('X-HTTP-Method_Override'));
// Connect to MongoDB
mongoose.connect(dbURI);
//var db = mongoose.connection;
// CONNECTION EVENTS
// When successfully connected
mongoose.connection.on('connected', function () {
console.log('Mongoose default connection open to ' + dbURI);
});
// If the connection throws an error
mongoose.connection.on('error',function (err) {
console.log('Mongoose default connection error: ' + err);
});
// When the connection is disconnected
mongoose.connection.on('disconnected', function () {
console.log('Mongoose default connection disconnected');
});
// If the Node process ends, close the Mongoose connection
process.on('SIGINT', function() {
mongoose.connection.close(function () {
console.log('Mongoose default connection disconnected through app termination');
process.exit(0);
});
});
// Test connection
mongoose.connection.once('open', function() {
console.log('Listening on port 3000... ');
app.listen(3000);
})
Output when I try and run node index.js is MonogError: getaddrinfo ENOTFOUND mongodb mongodb:127. The DB is currently running on port 27017.
I have tried
mongodb:\\"PCname"\d$\db\pclistapp
mongodb:\\localhost\d$\db\pclistapp
mongodb:"PCname"\d$\db\pclistapp
mongodb:localhost\d$\db\pclistapp
and none of them seem to work. I know the UNC works for \"PCname"\d$\db\pclistapp so I am not sure what the issue is.
DB Connection Issue
DB Operational

Took a long time but the mistake was simple. I re-wrote the code to condense the errors and it's not a UNC which I need to connect to but via HTTP. Fix that and I was off to the races.
Silly me.
Code:
var mongoURI = "mongodb://localhost:27017/pclistapp";
var MongoDB = mongoose.connect(mongoURI).connection;
MongoDB.on('error', function(err) { console.log(err.message); });
MongoDB.once('open', function() {
console.log("mongodb connection open");
});

Related

Why "Server is Connected" comes before the "Database is connected" in terminal of VScode in express app?

I just want to know Why "Server is Connected" comes before the "Database is connected" in terminal of VScode in express app?
Here is my code
const express = require("express");
const cors = require("cors");
const mongoose = require("mongoose");
const exercises = require("./routes/exercises");
const users = require("./routes/users");
require('dotenv').config();
const app = express();
const port = process.env.PORT || 8000;
app.use(cors());
app.use(express.json());
mongoose.connect("mongodb+srv://#cluster0.lzvul.mongodb.net/my_database?retryWrites=true&w=majority&useNewUrlParser=true&useUnifiedTopology=true");
const db = mongoose.connection;
db.on("error", console.error.bind(console, "connection error: "));
db.once("open", () => {
console.log("Connected successfully");
});
app.listen(port , () => {
console.log(`Server is running on localhost:${port}`);
})
First, take care of your credentials, use the .env file just like you used it for storing the port.
Now, talking about what happened to your code.
The mongoose.connection function returns a Promise, which means, a peace of code that will run along side the rest of your code if you don't specify that you want to wait for it to respond back.
For this reason, the server starts running before the database is properly connected, it takes longer for your application to get in contact with mongodb servers than it takes for express to get running.
I strongly recommend you to have a look at the Promise documentation to understand it deeper.
Anyway a possible solution for know is to await for the mongoose connection to be stablished and just then start your server
...
/*
Assuming you've put your mongodb URI in the MONGO_URI variable
at the .env file
*/
mongoose.connect(process.env.MONGO_URI)
.then(() => {
const db = mongoose.connection;
db.on("error", console.error.bind(console, "connection error: "));
db.once("open", () => {
console.log("Connected successfully");
});
app.listen(port , () => {
console.log(`Server is running on localhost:${port}`);
});
})
.catch((err) => {
console.log("Something went wrong with the database connection");
});
By using the .then method we are basically saying, we want to wait for this function to respond, and when it responds we want to execute this following function, where we call the rest of logic you wrote, server startup included.
That will make sure that the database initializes before the server and if something goes wrong with this process the server doesn't start.

Socket.io (emit, on) not working - Node JS

I am working on a node JS application, where I am trying to use socket.io following this tutorial. Until this tutorial everything is fine, even the client is connected to the server through the socket, as it display a message on connection. But I don't know why my code isn't working on emit, and on event, and event handler.
Below is my Code on server side :
const express = require("express");
const app = express();
const scrap = require("./algorithm");
const mysql = require("mysql");
const ms_connect = mysql.createConnection({
host:'localhost',
user:'root',
password:'',
database:'scrapper_db'
});
const server = app.listen(8000, function(){ console.log('Listening on 8000'); });
const io = require("socket.io").listen(server);
app.use(express.static(__dirname + "/"));
io.on("connection",function(socket){
console.log("Sockets Connection Made ! " + socket.id);
socket.emit("testing",{data:"I am tested"});
io.on("disconnect",function(){
console.log("Client Disconnected !");
})
})
//mySQL Conection
ms_connect.connect(function(err){
if(err) console.log(err);
ms_connect.query("Select * FROM test",function(err,rows,fields){
if(err) console.log("Error Executing Query");
})
})
app.get("/scrap",function(req,res){
res.sendFile(__dirname+"/index.html");
})
Client side code :
var socket = io.connect('http://localhost:8000/scrap');
console.log(socket.connected); //returns false :(
socket.on("testing", function(d) {
console.log(d);
});
In the client side, the socket.connected object returns false, but on server side it says connected. I don't know how , and
I am using third link from this socket.io cdnjs server.
You are doing io.connect('http://localhost:8000/scrap') but the scrap is not mentioned anywhere on the server side. It should be io.connect('http://localhost:8000/'). Pointing to your HTML file is not needed because the socket.io server and your webserver are unrelated.
Also as pointed out by #TommyBs you should use
socket.on('connect', () => { console.log(socket.connected); });
to check if you are connected because connecting is asynchronous so it will not have connected yet by the time you do console.log(socket.connected);
The whole client code would be
var socket = io.connect('http://localhost:8000');
socket.on('connect', () => { console.log(socket.connected); });
socket.on("testing", function(d) {
console.log(d);
});
Change http://localhost:8000/scrap to http://localhost:8000/ in the client code. You're connecting to the wrong route.

mongojs driver not connecting to mongodb

i have been trying to connect to my local mongodb using mongojs package but its not connecting at all. i have my mongo service running on http://127.0.0.1:27017/ and below is my code :
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var mongo= require('mongojs');
var db=mongo('catalog',['products']);
app.use(bodyParser.json);
//adding our first route name
db.on('connect', function () {
console.log('database connected')
})
app.get('/',function(req,res){
res.send('It Worked');
});
app.get('/products',(req,res)=>{
db.products.find(function (err,docs) {
if (err) {
res.json(err)
}else{
res.json(docs)
}
})
});
i have set event on connect to log if the connection is established but nothing is showing up.do you i could use mongoose or some other packages if it doesnt work at all?
mongojs doesn't fire the connect function until you make the first request to a collection. Make a request to your collection and the on('connect') function will fire.
Or in your case go to /products in your browser and you can see the database connected log in your terminal.
If you want to request records from your collection without going to /products in your browser then just write your query outside of your app.get('/products').
Make sure you add
app.listen(3000, function() {
console.log('server is running');
});
at the the end and go to localhost:3000/products in your browser.

Error when connecting to mongodb

I am using node-run-cmd package to start the mongodb server in my app.js file. I know this works because I can see the collections on Robomongo when my script is running as well as the mongod.exe in my list of running processes. The problem is trying to connect to the db called testDB. Below is the commented code.
//start mongodb server
//this works
var nrc = require('node-run-cmd');
var cmd = '..\\mongodb\\mongod --dbpath '+__dirname+'\\db';
nrc.run(cmd);
//setup
var express = require('express');
var MongoClient = require('mongodb').MongoClient;
var app = express();
app.use(express.static('public'));
app.set('view engine', 'ejs');
//connect to mongo
//this fails to connect to db testDB
var url = 'mongodb://localhost:27017/testDB';
MongoClient.connect(url, function(err, db) {
if(!err) {
console.log("connection successful");
}
else{
console.log(err.message)
}
});
Here is the err.message
failed to connect to server [localhost:27017] on first connect
Any idea what I am doing wrong here. My assumption is that the db connection is trying before the server has fully started but I am not completely sure.
EDIT:
so that's what it was, timing issue. I tried the following and it connected to the DB. Is there a graceful way of doing this other than what I have here?
function connect(){
var url = 'mongodb://localhost:27017/testDB';
MongoClient.connect(url, function(err, db) {
if (!err) {
console.log("connection successful");
}
else {
console.log(err.message)
}
});
}
setTimeout(connect, 10000);
You should use the callback in the node_run_cmd package (https://www.npmjs.com/package/node-run-cmd#callback-style).
Place your connect function inside the callback.
You will probably also want to only start express here as well.

Under heavy load, client connecting to a socket.io may miss the first packet with node.js

I am on Node.js v4.1.1 and working with socket.io
when client connected to server socket and start exchanging packages at that time first packet missed on server.
have you guys any idea what is the reason behind this? Please note that we have around 900 connection at a time.
var http = module.exports = require('http');
var app = module.exports = express();
var httpsOptions = {
key: fs.readFileSync('server.key'),
cert: fs.readFileSync('certificate.crt')
};
var Server = https.createServer(httpsOptions, app);
var io = module.exports = require('socket.io').listen(Server);
io.set("transports", ["xhr-polling", "web socket", "polling", "htmlfile"]);
io.sockets.on("connection", function(socket)
{
client.on('msg', function(request)
{
console.log("event get --> " + request);
});
client.on('error', function(exc)
{
console.log("ignoring exception: " + exc);
});
client.on('ping', function(request)
{
client.emit('pong', request);
client.removeListener('ping', function() {});
});
client.on('disconnect', function(reason)
{
console.log("socket disconnect " + reason);
});
});
In this case actually error not in socket or node.js. Error in mongodb , mongodb take so much load so all event's are late. Also new connection take load in sign up process.we just increase the configuration of mongodb and all working well.

Resources