connectIin to mangodb with js unlimited time - javascript

Good morning everyone ,
i tried to create a new data base with mangodb version msi 6.0 i made this code below:
var MongoClient = require('mongodb').MongoClient;
var url = "mongodb://localhost:27017/mydb";
MongoClient.connect(url, function(err, db) {
if (err) throw err;
console.log("Database created!");
db.close();
});
the first error is about MongooseServerSelectionError: connect ECONNREFUSED localhost:27017`
i changed the local host with the ip adress 127.0.0.1
NOW IT DOES NOT SHOW ANY ERROR BUT THE PROCESS TAKE UNLIMITED TIME !!!
THAKS!!!
Solution for the UNLIMITED TIME EXECUTION PROBLEM

please check if you are actually running the mongo on given port, and see:
MongoNetworkError: failed to connect to server [localhost:27017] on first connect [MongoNetworkError: connect ECONNREFUSED 127.0.0.1:27017]
https://www.mongodb.com/docs/manual/reference/connection-string/

Related

SequelizeConnectionError in Node.js application

I have strange problem and don't know in what place is the problem. I will be grateful for any help.
I have Node.js application which works fine in local windows 10 computer. I run this application successfully in Docker which is in CentOS server. This application works with remote MySQL and PostgreSQL databases. It worked correctly several days but yestoday I notice that I have error. Application can't connect to remote MySQL database anymore. In the same time I can connect to that remote MySQL database without any problem if I run application in my local computer or connect by DBeaver/dbForge tool.
MySQL.js:
const Sequelize = require('sequelize');
const sequelize = new Sequelize('database_name', 'username', 'password', {
host: 'host',
dialect: 'mysql'
});
sequelize.authenticate().then(() => {
console.log('Connection to database has been established successfully.');
}).catch(err => {
console.error('Unable to connect to database:', err);
});
module.exports = sequelize;
routes.js:
const express = require('express');
const router = express.Router();
const sequelize = require('../configurations/MySQL');
const Sequelize = require('sequelize');
const passport = require('passport');
require('../configurations/password')(passport);
router.post('/search_by_name', passport.authenticate('jwt', {session: false}, null), function(req, res) {
const token = getToken(req.headers);
if (token) {
sequelize.query("LONG SQL QUERY", {
replacements: {
name: req.body.name,
},
type: Sequelize.QueryTypes.SELECT
}).then((locations) => {
res.status(200).send(locations)
}).catch((error) => {
res.status(400).send(error);
});
} else {
return res.status(401).send({
status: false,
description: "Unauthorized"
});
}
});
As you can see I use sequelize library to connect application to remote MySQL database. The same library I use to connect to remote PostgreSQL database. As I said before error happens only when I try to connect to remote MySQL database in Docker. There is no error with PostgreSQL connection in Docker. Is it possible that problem inside Docker/network?
Dependencies:
"sequelize": "^4.42.0"
"mysql2": "^1.6.4"
I also thought that the reason of the problem can be because of much pools/connections and sequelize library don't close them automatically. For thats why I restarted docker сontainer several times hoping to confirm the theory. Unfortunately the error do not disappear.
How do you think, what happens?
Error:
Unable to connect to the database: { SequelizeConnectionError: connect ETIMEDOUT
at Utils.Promise.tap.then.catch.err (/node_modules/sequelize/lib/dialects/mysql/connection-manager.js:149:19)
at tryCatcher (/node_modules/bluebird/js/release/util.js:16:23)
at Promise._settlePromiseFromHandler (/node_modules/bluebird/js/release/promise.js:512:31)
at Promise._settlePromise (/node_modules/bluebird/js/release/promise.js:569:18)
at Promise._settlePromise0 (/node_modules/bluebird/js/release/promise.js:614:10)
at Promise._settlePromises (/node_modules/bluebird/js/release/promise.js:690:18)
at _drainQueueStep (/node_modules/bluebird/js/release/async.js:138:12)
at _drainQueue (/node_modules/bluebird/js/release/async.js:131:9)
at Async._drainQueues (/node_modules/bluebird/js/release/async.js:147:5)
at Immediate.Async.drainQueues [as _onImmediate] (/node_modules/bluebird/js/release/async.js:17:14)
at processImmediate (timers.js:632:19)
name: 'SequelizeConnectionError',
parent:
{ Error: connect ETIMEDOUT
at Connection._handleTimeoutError (/node_modules/mysql2/lib/connection.js:173:17)
at listOnTimeout (timers.js:324:15)
at processTimers (timers.js:268:5)
errorno: 'ETIMEDOUT',
code: 'ETIMEDOUT',
syscall: 'connect',
fatal: true },
original:
{ Error: connect ETIMEDOUT
at Connection._handleTimeoutError (/node_modules/mysql2/lib/connection.js:173:17)
at listOnTimeout (timers.js:324:15)
at processTimers (timers.js:268:5)
errorno: 'ETIMEDOUT',
code: 'ETIMEDOUT',
syscall: 'connect',
fatal: true }}
Try to add pool option when new Sequelize. Reference document
Sequelize will setup a connection pool on initialization so you should
ideally only ever create one instance per database if you're
connecting to the DB from a single process. If you're connecting to
the DB from multiple processes, you'll have to create one instance per
process, but each instance should have a maximum connection pool size
of "max connection pool size divided by number of instances". So, if
you wanted a max connection pool size of 90 and you had 3 worker
processes, each process's instance should have a max connection pool
size of 30.
const Sequelize = require('sequelize');
const sequelize = new Sequelize('database_name', 'username', 'password', {
host: 'host',
dialect: 'mysql',
pool: {
max: 15,
min: 5,
idle: 20000,
evict: 15000,
acquire: 30000
},
});
module.exports = sequelize;
Also, you can check more option at here
options.pool sequelize connection pool configuration
options.pool.max default: 5 Maximum number of connection in pool
options.pool.min default: 0 Minimum number of connection in pool
options.pool.idle default: 10000 The maximum time, in milliseconds,
that a connection can be idle before being released. Use with
combination of evict for proper working, for more details read
https://github.com/coopernurse/node-pool/issues/178#issuecomment-327110870
options.pool.acquire default: 10000 The maximum time, in milliseconds,
that pool will try to get connection before throwing error
options.pool.evict default: 10000 The time interval, in milliseconds,
for evicting stale connections. Set it to 0 to disable this feature.
options.pool.handleDisconnects default: true Controls if pool should
handle connection disconnect automatically without throwing errors
options.pool.validate A function that validates a connection. Called
with client. The default function checks that client is an object, and
that its state is not disconnected
In the simple terms i want to say that these type of error comes when your some configuration wrong entered. these are :
DB Name
Username
Password
so please cross verify your these things in your congif.json file
I would recommend to check the Database Hostname. Please try to resolve the hostname, if it is given IP address instead of domain. This would resolve the issue.

How to install and use mongodb with node js?

I am very new to MongoDB and node.
So first of all:
How can I install MongoDB using the terminal on a Mac computer
Then how can I connect MongoDB with node?
How can I create a database in MongoDB using node?
Any help is appreciated. Thank You.
var MongoClient = require('mongodb').MongoClient;
var url = "mongodb://localhost:8080/mydb";
MongoClient.connect(url, function(err, db){
if(err)
{
console.log('error');
throw err;
}
else
{
console.log('success');
}
});
I tried this code but it shows an error.
This is the error I received:
You have to open the MongoDB server first.
Do this:
Go to the directory where mongo is installed: i.e.: <mongodb-install-directory>/bin
Start the server by : ./mongod --dbpath <mongo-data-directory>

Can't start MongoDB on localhost for node.js

I am a beginner to node.js and MongoDB. I am trying to setup a basic project like so.
In my project dir I run node init, accept the default values and then run npm install --save mongodb. In my index.js I have the following code:
// Import the mongodb module
var mongo = require('mongodb');
var MongoClient = require('mongodb').MongoClient;
var url = "mongodb://localhost:3333/mydb";
MongoClient.connect(url, function(err, db) {
if (err) throw err;
console.log("Database created!");
db.close();
});
Now when I run node index.js I get the following error:
failed to connect to server [localhost:3333] on first connect [MongoNetworkError: connect ECONNREFUSED 127.0.0.1:3333]
I have tried changing the port number but still get the same error. What am I doing wrong here?
By default the MongoDB server is running on port 27017. You need to change the connection string to mongodb://localhost:27017/mydb.
First you need to install MongoDB if you don't already have it installed. Visit MongoDB site to download.
Follow the instructions there on how to start it up and running, after that try running your app again.
Also by default MongoDB runs on port 27017 so your url should point to localhost:27017.
// Import the mongodb module
var mongo = require('mongodb');
var MongoClient = require('mongodb').MongoClient;
var url = "mongodb://localhost:27017/mydb";
MongoClient.connect(url, function(err, db) {
if (err) throw err;
console.log("Database created!");
db.close();
});

Meteor - Uncaught Error: Cannot find module 'mongodb'

I'm trying to establish a connection between my Meteor application and my MongoDB Atlas database.
I have the following bit of JavaScript:
var MongoClient = require('mongodb').MongoClient, format = require('util').format;
MongoClient.connect('<MyMongoURL>', function (err, db) {
if (err) {
throw err;
} else {
console.log("successfully connected to the database");
db.collection('largeTreeMap', function(err, docs) {
// Check for error
if(err) return console.log(err);
// Walk through the cursor
docs.find().each(function(err, doc) {
// Check for error
if(err) return console.err;
// Log document
console.log(doc);
})
});
}
db.close(); });
I added this to a blank JS document called test.js and upon running
node test.js
In my command line it returned the success message and data:
So now that I know the connection can be established I added the code to my Meteor project. I created a basic button and onClick the connection to MongoDB should completed.
However, instead I receive the following console error:
I understand from reading various Stack questions that this is a result of not running npm install mongodb in the project directory. However, I have tried doing this and the terminal returns:
Does any body know why the MongoDB is failing to install and preventing me from connecting to MongoDB in my application?
Any help would be much appreciated,
Many thanks,
G
You're trying to connect to the Mongo instance from the client, which is probably not what you want.
The mongodb npm package supports only Node.js, not JavaScript in the browser, as you can see from this line in its package.json
"engines": {
"node": ">=0.10.3"
},
In the case that worked, you are running it with Node.
What you probably want to do is to set the MONGO_URL environment variable to the Mongo Atlas instance, and leave the implementation of connecting / updating to Meteor itself.

Getting Mongo to Connect to Express App

Yosemite Mongo user working through a MEAN book. I've been following the steps exactly, but the MongoDB isn't connecting as expected. I installed Mongo once before to mess around with importing data, but didn't get too far. Below is all the Mongo related code I have besides package.json:
In app.js I have require('./app_server/models/db'); and in that folder I have:
var mongoose = require( 'mongoose' );
var dbURI = 'mongodb://localhost/Loc8r';
mongoose.connect(dbURI);
// CONNECTION EVENTS
mongoose.connection.on('connected', function () {
console.log('Mongoose connected to ' + dbURI);
});
mongoose.connection.on('error',function (err) {
console.log('Mongoose connection error: ' + err);
});
mongoose.connection.on('disconnected', function () {
console.log('Mongoose disconnected');
});
I am expecting to get
Express server listening on port 3000
Mongoose connected to mongodb://localhost/Loc8r
But instead get:
Mongoose disconnected
Mongoose connection error: Error: failed to connect to [localhost:27017]
I've tried changing a line to var dbURI = 'mongodb://localhost:3000/Loc8r'; because that's what my computer is using, but then get this error:
Mongoose disconnected
Mongoose connection error: Error: connection closed
Any help is much appreciated thanks.
Mongo was missing the folders it needed MongoDB not working. "ERROR: dbpath (/data/db) does not exist."
Then the server had to be run with "mongod"

Categories