Database is not running in mongodb atlas due to unhandled promise exception - node.js

My code is running fine in localhost with no warnings but when I'm changing my connection string to the string provided by mongodb atlas, following errors are showing which you can see in the below pic and my browser keeps circulating plz guide me what I'm doing wrong
(node:13700) DeprecationWarning: 'open()' is deprecated in mongoose >=
4.11.0,
use 'openUri() instead, or set the 'useMongoClient' option if using 'connect()' or 'createConnection()'. See
http://mongoosejs.com/docs/4.x/docs/connections.html#use-mongo-client
(Use 'node --trace-deprecation... to show where the warning was
created)
Server started on port 3000
Error [MongoError]: failed to connect to server [undefined:27017] on first connect [Error: getaddrinfo ENOTFOUND undefined
at GetAddrInfoReqwrap.onlookup [as oncomplete] (dns.js:67:26) {}] name: 'MongoError'
at Pool. (C:\Users\Umer\Desktop\node\Alhamdulillah, complete webapp\All Validations Completed\node_modules\mongodb-core\lib\topologies\server.js: 336:35)
at Pool.emit (events.js:315 :20) at Connection.
(C:\Users\Umer\Desktop\node\Alhamdulillah, complet e webapp\A11
Validations Completed\node_modules\mongodb-core\lib\connection\poo1
Lis:280:12)
screenshot

According to the problem that you're facing, it is because you're coding the deprecated method of connecting to the MongoDB.
Your database.js file seems okay but I would suggest that you use dotenv and not a separate file for your secrets
But in your app.js file, kindly completely change the way you're connecting to MongoDB.
const config = require('./config/database')
const options = {useUnifiedTopology: true, useNewUrlParser: true}
mongoose.connect(config.mongoURI, options).then(
()=> console.log('connected to mongodb'),
(reason)=> console.error(`Error: ${reason}`)
)
// All of your other code ahead.
Happy Coding!

Related

Error: No event 'socketConnect' in state 'SentPrelogin'

I am trying to connect my SQL Server database with node.js using knex but I am facing issue
Error: No event 'socketConnect' in state 'SentPrelogin'
at Connection.dispatchEvent (C:\Users\temp\Documents\PRactice\node_modules\tedious\lib\connection.js:1281:26)
at Connection.socketConnect (C:\Users\temp\Documents\PRactice\node_modules\tedious\lib\connection.js:1303:10)
at C:\Users\temp\Documents\PRactice\node_modules\tedious\lib\connection.js:1145:12
at Socket.onConnect (C:\Users\temp\Documents\PRactice\node_modules\tedious\lib\connector.js:106:7)
at Socket.emit (events.js:314:20)
at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1131:10)
Emitted 'error' event on Connection instance at:
at Connection.dispatchEvent (C:\Users\temp\Documents\PRactice\node_modules\tedious\lib\connection.js:1281:12)
at Connection.socketConnect (C:\Users\temp\Documents\PRactice\node_modules\tedious\lib\connection.js:1303:10)
[... lines matching original stack trace ...]
at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1131:10)
[nodemon] app crashed - waiting for file changes before starting...
My code is
var knex = require('knex')({
client: 'mssql',
version:"7_1",
connection: {
user: 'sa',
password: 'Admin#123',
server: 'localhost',
database: 'Demo'
}
});
knex.select("*").from("Country")
.then(function (depts){
depts.forEach((dept)=>{ //use of Arrow Function
console.log({...dept});
});
}).catch(function(err) {
// All the error can be checked in this piece of code
console.log(err);
}).finally(function() {
// To close the connection pool
knex.destroy();
});
You need to add a missing dependency:
npm install --save tedious
As of knex v0.95.0 you'll need to use the tedious library instead of mssql when connecting to an MSSQL database. According to the knex upgrade instructions:
MSSQL driver was completely reworked in order to address the multitude of connection pool, error handling and performance issues. Since the new implementation uses tedious library directly instead of mssql, please replace mssql with tedious in your dependencies if you are using a MSSQL database.
Installing the package above should resolve your issue. I also had to set the encrypt option to false when connecting to my local database to avoid this error:
ConnectionError: Failed to connect to localhost:1433 - self signed certificate

when I try to connect to mongodb I got these error

(node:9804) DeprecationWarning: current Server Discovery and Monitoring engine is deprecated, and will be removed in a future version. To use the new Server Discover and Monitoring engine, pass option { useUnifiedTopology: true } to the MongoClient constructor.
(Use node --trace-deprecation ... to show where the warning was created)
Connection errorMongoNetworkError: failed to connect to server [localhost:27017] on first connect [Error: connect ECONNREFUSED 127.0.0.1:27017
at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1146:16) {
name: 'MongoNetworkError'
}]
keep your mongodb compass open then try running the code from your IDE.

How to use MongoDB with codesandbox?

I have been following an Udemy course to learn mongodb, and since the tutor uses a cloud based ide (cloud9), I have also decided to use the same. However, since cloud9 now requires AWS account I thought of using CodeSandbox. But I can't figure out how to start Mongo server on it.
After installing both Mongod and MongoDB, if I try to run the app.js, it gives me error:
(node:1297) UnhandledPromiseRejectionWarning: MongoNetworkError: failed to connect to server [localhost:27017] on firstconnect [MongoNetworkError: connect ECONNREFUSED 127.0.0.1:27017]
at Pool.<anonymous> (/sandbox/node_modules/mongodb/lib/core/topologies/server.js:433:11)
at Pool.emit (events.js:198:13)
at createConnection (/sandbox/node_modules/mongodb/lib/core/connection/pool.js:577:14)
at connect (/sandbox/node_modules/mongodb/lib/core/connection/pool.js:1007:11)
at makeConnection (/sandbox/node_modules/mongodb/lib/core/connection/connect.js:31:7)
at callback (/sandbox/node_modules/mongodb/lib/core/connection/connect.js:247:5)
at Socket.err (/sandbox/node_modules/mongodb/lib/core/connection/connect.js:276:7)
at Object.onceWrapper (events.js:286:20)
at Socket.emit (events.js:198:13)
at emitErrorNT (internal/streams/destroy.js:91:8)
at emitErrorAndCloseNT (internal/streams/destroy.js:59:3)
at process._tickCallback (internal/process/next_tick.js:63:19)
(node:1297) UnhandledPromiseRejectionWarning: Unhandled promise rejection. Thiserror originated either by throwing inside of an async function without a catchblock, or by rejecting a promise which was not handled with .catch(). (rejection id: 1)
(node:1297) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
If I try to run mongod, it says
mongod: command not found
This is my app.js
var express = require("express");
var app = express();
var bodyParser = require("body-parser");
var mongoose = require("mongoose");
mongoose.connect("mongodb://localhost/yelp_camp");
I have tried installing mongo and mongod using codesandbox's UI , using terminal (npm install), and doing what cloud9's docs say (I know it should not work but I can't find any Codesandbox documentation)
Is it possible to do this in codesandbox or will I have to use MongoAtlas?
Thanks in advance!
I think there's no database hosting on CodeSandbox, so you should use an external service.
Some services you can use:
MLab (Free plan)
ObjectRocket (Free trial)
Compose (Free trial)
MongoAtlas
MLab example
Set up a database at MLab
Copy and paste the connection string
A simple example function would be:
let initMongo = async () => {
try {
await mongoose.connect(
"mongodb://<dbuser>:<dbpassword>#ds123456.mlab.com:49878/testdatabase",
{
useNewUrlParser: true,
useUnifiedTopology: true
}
);
return console.log("Database connected!");
} catch (e) {
return console.log("Database error!", e.message);
}
};
Here's the documentation of CodeSandbox.
CodeSandbox has a starter for connecting to hosted MongoDB like Atlas - see https://codesandbox.io/s/mongodb-database-example-starter-v3ker

node can't connect to Mongo -- Error: getaddrinfo ENOTFOUND undefined undefined:27017

When I try to start my express server with node index.js I get the following error message:
*path/to/project*/node_modules/mongodb/lib/server.js:242
process.nextTick(function() { throw err; })
^
Error: getaddrinfo ENOTFOUND undefined undefined:27017
at errnoException (dns.js:26:10)
at GetAddrInfoReqWrap.onlookup [as oncomplete] (dns.js:77:26)
There are many questions on Stack Overflow with similar error messages but they are mostly due to either not running mongod or typos.
I am running mongod, I can connect to mongo via the terminal. I changed some code and hit some errors, but then started fresh from working code. The current code worked to connect to MongoDB before (and production version works with the same code).
I can also run an express server and connect to MongoDB on the same machine with different node projects with similar setups.

Ghost Blog - Unable to connect with mysql

After deploying the Ghost blogging platform with success, i tried to configure it to use Mysql instead of sqllite3 using this database section of their config page, which says:
Database
By default, Ghost comes configured to use an SQLite database, which
requires no configuration.
Alternatively Ghost can also be used with a MySQL database by changing
the database configuration. You must create a database and user first,
you can then change the existing sqlite config to something like:
database: { client: 'mysql', connection: {
host : '127.0.0.1',
user : 'your_database_user',
password : 'your_database_password',
database : 'ghost_db',
charset : 'utf8' }
}
So ok, the setup is straight forward. but i'm still unable to connect ghost with mysql. The error i receive after starting the platform using npm start --production is :
> ghost#0.6.2 start /var/www/ghost
> node index
Migrations: Database initialisation required for version 003
Migrations: Creating tables...
Migrations: Creating table: posts
ERROR: connect ECONNREFUSED
Error: connect ECONNREFUSED
at errnoException (net.js:905:11)
at Object.afterConnect [as oncomplete] (net.js:896:19)
--------------------
at Protocol._enqueue (/var/www/ghost/node_modules/mysql/lib/protocol/Protocol.js:110:48)
at Protocol.handshake (/var/www/ghost/node_modules/mysql/lib/protocol/Protocol.js:42:41)
at Connection.connect (/var/www/ghost/node_modules/mysql/lib/Connection.js:98:18)
at /var/www/ghost/node_modules/knex/lib/dialects/mysql/index.js:105:16
at tryCatch2 (/var/www/ghost/node_modules/bluebird/js/main/util.js:53:21)
at Promise._resolveFromResolver (/var/www/ghost/node_modules/bluebird/js/main/promise.js:544:13)
at new Promise (/var/www/ghost/node_modules/bluebird/js/main/promise.js:84:37)
at Client_MySQL.acquireRawConnection (/var/www/ghost/node_modules/knex/lib/dialects/mysql/index.js:104:10)
at Object.create (/var/www/ghost/node_modules/knex/lib/pool.js:33:19)
at Object.Pool.createResource (/var/www/ghost/node_modules/knex/node_modules/generic-pool-redux/pool.js:288:12)
I'm not sure what could be wrong, since i have other applications using mysql working without any problems.
Thanks in advance.
connection refused = tcp connection was attempted, but nothing is listening on the port, or was explicitly denied. Unless you explicitly enabled TCP support in mysql (and have the correct ip/port), you should probably be using a local unix-domain socket instead.

Resources