MongoDB - MongoError: connect ECONNREFUSED - javascript

I keep getting an error when trying to connect mongoDB. I know there are many questions similar to this one and I have checked all of them and haven't found a solution for my issue.
Here is the exact error:
connection error: { MongoError: connect ECONNREFUSED 127.0.0.1:21017
name: 'MongoError'
message: connect ECONNREFUSED 127.0.0.1:21017
I looked at some other solutions and they say to adjust the mongo.conf file but I can't seem to find the file on my system and I've downloaded MongoDB.
Here is my full code:
var express = require('express');
var router = express.Router();
var mongoose = require('mongoose');
$ = require('cheerio');
/* GET home page. */
mongoose.connect('mongodb://localhost/');
var db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function() {
console.log('Connected to database');
// we're connected!
});
var pageInfo = {
title: 'JotIT',
owner: 'Emmanuel Obogbaimhe',
message: 'Hi welcome to JotIT. A quick, simple and easy to use note taker.',
date: Date.now(),
age: 22
};
router.get('/', function(req, res, next) {
res.render('index', {
title: pageInfo.title,
author: pageInfo.owner,
message: pageInfo.message,
date: pageInfo.date,
age: pageInfo.age
});
});
module.exports = router;

The reason for getting that kind of error: {MongoError: connect ECONNREFUSED 127.0.0.1:21017}, is that Mongo process is not running on that PORT, or not running at all.
For first check out if mongo process is running:
service mongod status //for Linux machine
For second - check the port of mongo process:
nmap -p- localhost //for Linux machine

For windows, open another terminal and cd into the apps root directory. Then, run $ mongod.exe. I would recommend placing the following into a test.js file:
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost:27017/test.js');
var db = mongoose.connection;
db.on("error", function(error){
console.error("Connection error : " + error)
});
db.once('open', function() {
console.log('Connected to database');
db.close(function(){
console.log("db connection closed");
});
});
Go back to the original terminal and run $ node test.js

I had the same error, It looks like and bad closing in preview mongodb session I just did and It worked out fine
sudo service mongod stop
sudo service mongod start

Had the same problem, caused by running out of hard drive memory space. This caused mongod to keep crashing after restarting it.
Simply increasing memory space of the server, and restarting mongod (either manually or via reboot when service restarts automatically) solved the issue.

Try this
var express = require('express');
var router = express.Router();
var mongoose = require('mongoose');
$ = require('cheerio');
/* GET home page. */
mongoose.connect('mongodb://localhost:27017/db-dev');
or try with
mongoose.connect('mongodb://0.0.0.0:27017/db-dev');

change your mongoose connection code to:
mongoose.connect('mongodb://localhost:27017/yourdb');

This error can be solved by replacing localhost in the following code with the address of localhost which is 127.0.0.1.
mongoose.connect('mongodb://localhost/');
Try this -> mongoose.connect('mongodb://127.0.0.1/');

Related

Nodemon: app crashed waiting for file changes before starting... on Windows

I implemented express code with the mongoose database but I have faced "nodemon crushed" error for that I followed the below techniques but still, now I have faced this error.
Node version: v16.14.2
NPM version: 8.5.0
I have followed some steps to solve this issue and that is given below,
Open Windows Task Manager is given in the attached file
End Task (Node.js JavaScript Runtime)
But the problem is not solved!
Here is the code of server.js
const express = require('express')
const mongoose = require('mongoose')
const app = express()
mongoose.connect('mongodb://localhost:27017/my-students');
const studentRoute = require('./api/routes/studentsRoute');
//========> Routing Starting
app.use('/api/students', studentRoute);
//========> Routing End
//========> MongoDB Database connection and Check
const db = mongoose.connection;
db.on('error', (err) =>{
console.log(err);
})
db.once('open', ()=>{
console.log("Database connection Established!")
})
const PORT = process.env.PORT || 3000;
app.listen(PORT, () =>{
console.log(`Server running on PORT #${PORT}`)
})
Windows Task Manager where I end the task by clicking "End Task" of "Node.js JavaScript Runtime" but it was not solved the issue and the Task Manager file attached below,
Error screenshot is given below the attached file,
The problem is arising from this line
const studentRoute = require('./api/routes/studentsRoute');
check if you have this included in that file
module.exports = router
Reference: TypeError: Router.use() requires middleware function but got a Object

React: Trying to connect index.js to database but its not working

So i built a frontend where you can fill in a movie name, a review and submit it to a database. Now im trying to connect a mysql database i created to the index.js , so that it gets filled with the first entry. Im trying to accomplish it like this:
const express = require('express');
const app = express();
const mysql = require('mysql');
const db = mysql.createPool({
host: "localhost",
user: "root",
password:"password",
database:'CRUDDatabase',
});
app.get('/', (req, res) => {
const sqlInsert = "INSERT INTO Movie_Reviews(movieName, movieReview) VALUES (1,'inception', 'good movie');"
db.query(sqlInsert, (err, result) =>{
res.send("change done");
});
})
app.listen(3001, () => {
console.log("running on port 3001")
})
But somehow the frontend gets the text ive send "Change done" but the database still doesnt show any entries. Any ideas where my mistake may be? Is it a code mistake or does it have to do with me db configuration. In mysql workbench i just created a default connection without changing anything.
EDIT: The Error seems to be the following:
Error: ER_NOT_SUPPORTED_AUTH_MODE: Client does not support authentication protocol requested by server; consider upgrading MySQL client
EDIT:
The following comment here solved my problem:
Execute the following query in MYSQL Workbench ALTER USER 'root'#'localhost' IDENTIFIED WITH mysql_native_password BY 'password'; Where root as your user localhost as your URL and password as your password Then run this query to refresh privileges: flush privileges; Try connecting using node after you do so. If that doesn't work, try it without #'localhost' part.
I think you have an error in your code but you are not showing it as you don't test in err variable, try this code in order to show what error you are getting:
const express = require('express');
const app = express();
const mysql = require('mysql');
const db = mysql.createPool({
host: "localhost",
user: "root",
password:"password",
database:'CRUDDatabase',
});
app.get('/', (req, res) => {
const sqlInsert = "INSERT INTO Movie_Reviews(movieName, movieReview) VALUES (1,'inception', 'good movie');"
db.query(sqlInsert, (err, result) =>{
if(err) {
console.log(err);
res.send(err.toString());
}
res.send("change done");
});
})
app.listen(3001, () => {
console.log("running on port 3001")
})
So as Med Amine Bejaoui pointed out in a comment, the solution is:
Execute the following query in MYSQL Workbench ALTER USER 'root'#'localhost' IDENTIFIED WITH mysql_native_password BY 'password'; Where root as your user localhost as your URL and password as your password Then run this query to refresh privileges: flush privileges; Try connecting using node after you do so. If that doesn't work, try it without #'localhost' part.

nodeJS socket.io on Raspberry Pi doesnt seem to be working

I am new to nodeJS...and programming. But I have tried to get this bit of code to work and I cannot understand why it does not seem to work. Whats worse is I do not know how to troubleshoot it either. If I use console.log statements, I can see that once I launch the webpage, it DOES connect, but the webpage never gets a message from the nodeJS server and the server never gets a message from the webpage. I am using Chrome browser.
server.js:
var express = require('express'),
app = express(),
server = require('http').createServer(app),
io = require('socket.io').listen(server);
server.listen(80);
app.use(express.static(__dirname + '/public'));
app.get('/', function (req, res) {
res.sendfile(__dirname + '/index.html');
});
var SerialPort = require('serialport');
var portName = process.argv[2];
var sp = new SerialPort(portName, {
baudRate: 9600,
dataBits: 8,
parity: 'none',
stopBits: 1,
flowControl: false
});
io.sockets.on('connected', function (socket) {
socket.emit('connected', {
data: 'connected'
});
socket.on('connected', function (data) {
console.log(data);
//Code
console.log('Sending Packet. Contents:');
sp.write(packet);
console.log(packet);
console.log('Packet Sent');
});
});
I launch it from command prompt on raspbery pi zero w:
sudo node server.js /dev/ttyACM0
The index.html references the interface.js. The top part of interface.js:
$(document).ready(function() {
// Connect to the node.js server. Gets server's local ip.
// Using this method robot can only be connected to on
// local network.
var ip = location.host;
var socket = io.connect(ip); // Connects to server
// Upon establishing a connection to the socket.io server...
socket.on('connected', function (data) {
console.log(data);
// Send out a message to the server
socket.emit('connected', { command: 'nothing' });
});
When I have console.log statements in the interface.js I get them until the socket.on statement.
node -v
v6.4.0
npm -v
5.3.0
npm list socket.io
socket.io#2.0.3
uname -m
armv6l
Edit: Updated messaging commands. Same issue. Also
Well, turns out I have the wrong version of socket.io.js. So. That was a week of learning. Thanks for the help.

Nodejs App doesnt spawn python child process when Nodejs app started using Systemd

I'd like to start my node js application on boot. Therefore I start a service from Systemd:
[Unit]
Description=Node.js server
After=network.target
[Service]
ExecStart=/usr/bin/node /var/www/Raspberry-Pi-Status/js/server.js
Restart = always
RestartSec=10
StandardOutput=syslog
StandardError=syslog
SyslogIdentifier=nodejs-server
Environment=NODE_ENV=production PORT=8000
Environment=PYTHONPATH=/usr/bin/python
[INSTALL]
WantedBy=multi-user.target
The server.js looks like this:
var util = require('util'),
spawn = require('child_process').spawn,
py = spawn('python',['temperature.py'],{detached: true});
var mysql = require('mysql');
var connection = mysql.createConnection({
host : 'localhost',
user : 'monitor',
password : 'password',
database : 'temps'});
var app = require('http').createServer(handler),
io = require('socket.io').listen(app),
fs = require('fs'),
sys = require('util'),
exec = require('child_process').exec,
child;
// Listen on port 8000
app.listen(8000);
// If all goes well when you open the browser, load the index.html file
function handler(req, res) {
fs.readFile(__dirname+'/../index.html', function(err, data) {
if (err) {
// If no error, send an error message 500
console.log(err);
res.writeHead(500);
return res.end('Error loading index.html');
}
res.writeHead(200);
res.end(data);
});
}
py.stdout.on('data', function(data){
console.log('testing');
date = new Date().getTime();
temp = parseFloat(data);
io.sockets.emit('temperatureUpdate',date,temp);
});
// When we open the browser establish a connection to socket.io.
// Every 5 seconds to send the graph a new value.
io.sockets.on('connection', function(socket) {
console.log('user connected');
});
The node.js application should start a python script which reads out a temperature sensor. When I start node.js via the console everything works fine. However, when I start from Systemd, the python script is not spawned.
What's the problem there? Am I missing something?
Thanks in advance
Alexander
An issue could be the difference in the current working directory when run manually vs systemd. The spawn call used is documented has a default to inherit the current working directory.
When run via the shell, that would be whatever directory you are currently in. In man systemd.exec, you find the "WorkingDirectory=` directive, which documents systemd's default current working directory: "defaults to the root directory when systemd is running as a system instance".
So if your temperature.py is located in /var/www/Raspberry-Pi-Status, then set:
workingDirectory=/var/www/Raspberry-Pi-Status in your `[Service]` section.

nodejs express mongoose connect to db error

I use nodejs express and mongoose to connect mongodb,I've created a config.js in root folder.I am trying to exports db connect in db.js and trying to import in adminController.js
But when I run the server and refresh the browser ,it log me some errors and not log my log in terminal.
config.js
module.exports = {
cookieScret:'ThreeKingdoms',
db:'threekingdoms',
host:'localhost',
port:27017
}
db.js
var mongoose = require('mongoose'),
config = require('../config'),
connection = mongoose.connection;
module.exports = function(mongoose){
return mongoose.connect('mongodb://'+config.host+'/'+config.db);
}
adminController.js
var express = require('express'),
router = express.Router(),
mongoose = require('mongoose'),
mainInfo = require('../models/admin'),
db = require('../models/db');
router.get('/', function(req, res) {
res.render('admin', { title: 'hey im here!how are you' });
db.on('error',console.error.bind(console, 'connection error:'));
db.once('open', function() {
console.log(db)
});
console.log(db)
});
router.post('/',function(req,res,next){
//console.log(req.body)
var mainInfo = mongoose.model('mainInfo');
})
module.exports = router;
question files is in red box
terminal error
I am new to nodejs,so please help me,Thanks
First, it seems that you don't have kerberos installed. Please run npm install kerberos.
Also, the line
Can't set headers after they're sent
Suggests you're trying to modify/send the response after it was already sent back to the client, and that's the error you're getting.
finally it is work now,but it doesn't matter with 'kerberos' ,it is i use wrong way to export my module.terminal still log me 'kerberos undefined' but web can work,i think maybe some time i will try to figure this question out.thanks for your attention

Categories

Resources