Failed to connect to MongoDB ( remote server ) - node.js

I am trying to deploy an Angular/NodeJS app on the server I just bought.
( http://o2switch.fr is the provider )
I managed to deploy the angular part, but I have trouble with the connexion to mongoDB
When I launch app.js in my terminal, it says :
(node:30382) UnhandledPromiseRejectionWarning: MongoNetworkError: failed to connect to server [cluster0-shard-00-00.cgjma.mongodb.net:27017] on first connect [MongoNetworkError: connect ECONNREFUSED 15.237.158.132:27017]
at Pool.<anonymous> (/home/ewhc6963/nodevenv/node/10/lib/node_modules/mongoose/node_modules/mongodb/lib/core/topologies/server.js:441:11)
at Pool.emit (events.js:198:13)
at createConnection (/home/ewhc6963/nodevenv/node/10/lib/node_modules/mongoose/node_modules/mongodb/lib/core/connection/pool.js:564:14)
at connect (/home/ewhc6963/nodevenv/node/10/lib/node_modules/mongoose/node_modules/mongodb/lib/core/connection/pool.js:1014:9)
at makeConnection (/home/ewhc6963/nodevenv/node/10/lib/node_modules/mongoose/node_modules/mongodb/lib/core/connection/connect.js:32:7)
at callback (/home/ewhc6963/nodevenv/node/10/lib/node_modules/mongoose/node_modules/mongodb/lib/core/connection/connect.js:300:5)
at TLSSocket.err (/home/ewhc6963/nodevenv/node/10/lib/node_modules/mongoose/node_modules/mongodb/lib/core/connection/connect.js:330:7)
at Object.onceWrapper (events.js:286:20)
at TLSSocket.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:30382) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1)
(node:30382) [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.
Basically, it doesn't manage to connect to MongoDB even though in localhost, it works fine.
app.js :
mongoose.connect(config.DB_URI, function(err, db){
if (err) throw err;
console.log('Connected to database');
}, { useNewUrlParser: true });
config/server.js :
module.exports = {
DB_URI : 'mongodb+srv://pseudo:password#cluster0.cgjma.mongodb.net/rank'
}

Mongo connection fails. So you should handle the promise rejection. You may use .catch() method to do that. You can check this link.

Related

(node:1928) UnhandledPromiseRejectionWarning: MongooseError: Operation `users.createIndex()` buffering timed out

Getting the following error when I tried to estalish connection to my MongoDB Atlas.
[nodemon] starting `node index.js`
Note-It backend listening at http://localhost:5000
(node:1928) UnhandledPromiseRejectionWarning: MongooseError: Operation `users.createIndex()` buffering timed out after 10000ms
at Timeout.<anonymous> (C:\Users\Meet\OneDrive\Desktop\note-it-backend-api\backend\node_modules\mongoose\lib\drivers\node-mongodb-native\collection.js:149:23)
at listOnTimeout (internal/timers.js:557:17)
at processTimers (internal/timers.js:500:7)
(Use `node --trace-warnings ...` to show where the warning was created)
(node:1928) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1)
(node:1928) [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.
***********************Connected to MongoDB successfully***********************
I cant make any HTTP requests because of this
The db.js contents are :
const mongoose = require('mongoose');
// Connection string for MongoDB ATLAS
const mongoURL = "mongodb+srv://new-meeti:<password>#meet-dev.cc0qw.mongodb.net/?retryWrites=true&w=majority"
const connectToMongo = () => {
// .connect method taks 2 args, 2nd one is a callback function
mongoose.connect(mongoURL, () => {
console.log("***********************Connected to MongoDB successfully***********************");
})
}
module.exports = connectToMongo;
This was more than a year old project hosted on heroku but then I had to shift to to some other hosting service so again deploying is getting problematic due to various deprecation issues I think.
A help would be really appreciated. Thanks :)
PS : I checked my Network access on the MongoDB Atlas and 0.0.0.0/0 (includes your current IP address) is active.

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

DiscordJS and Linux's Screen

I'm facing an issue with discordjs and i don't understand it. I run "node main.js" into a linux screen, detach it, go to sleep and when i come back, it crashed. Could you enlight me ?
# screen -r BotApex
(node:6559) [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.
events.js:180
throw err; // Unhandled 'error' event
^
Error [ERR_UNHANDLED_ERROR]: Unhandled error. ([object Object])
at Client.emit (events.js:178:17)
at WebSocketConnection.onError (/root/ApexLegendsSnipeBot/node_modules/discord.js/src/client/websocket/WebSocketConnection.js:374:17)
at WebSocket.onError (/root/ApexLegendsSnipeBot/node_modules/ws/lib/event-target.js:128:16)
at WebSocket.emit (events.js:189:13)
at _receiver.cleanup (/root/ApexLegendsSnipeBot/node_modules/ws/lib/websocket.js:211:14)
at Receiver.cleanup (/root/ApexLegendsSnipeBot/node_modules/ws/lib/receiver.js:557:13)
at WebSocket.finalize (/root/ApexLegendsSnipeBot/node_modules/ws/lib/websocket.js:206:20)
at TLSSocket.emit (events.js:189:13)
at emitErrorNT (internal/streams/destroy.js:82:8)
at emitErrorAndCloseNT (internal/streams/destroy.js:50:3)
Looks like your bot ran into an error event while you were away. If you don't handle error events they usually make your bot crash. To prevent the bot from crashing, simply add an error listener:
client.on("error", info => {
console.log('Error event:\n' + JSON.stringify(info));
// handle the error here
});
Please keep in mind that the error event has been called for some reason and that you should handle the error afterwards.

Node.js server not working all of a sudden

It worked fine yesterday and now it's giving me this error. The API I created worked fine and all of the requests worked, now I have no idea what's wrong.
I used ng serve for my Angular app and node app.js for my API server and everything worked fine, why isn't it connecting now?
Running on port 4000...
(node:13096) DeprecationWarning: current URL string parser is deprecated, and will be removed in a future version. To use the new parser, pass option { useNewUrlParser: true } to MongoClient.connect.
(node:13096) UnhandledPromiseRejectionWarning: MongoNetworkError: failed to connect to server [localhost:27017] on first connect [MongoNetworkError: connection 0 to localhost:27017 timed out]
at Pool.<anonymous> (C:\Users\Heiko\Documents\parkingApi\node_modules\mongodb-core\lib\topologies\server.js:564:11)
at Pool.emit (events.js:182:13)
at Connection.<anonymous> (C:\Users\Heiko\Documents\parkingApi\node_modules\mongodb-core\lib\connection\pool.js:317:12)
at Object.onceWrapper (events.js:273:13)
at Connection.emit (events.js:182:13)
at Socket.<anonymous> (C:\Users\Heiko\Documents\parkingApi\node_modules\mongodb-core\lib\connection\connection.js:257:10)
at Object.onceWrapper (events.js:273:13)
at Socket.emit (events.js:182:13)
at Socket._onTimeout (net.js:448:8)
at ontimeout (timers.js:424:11)
at tryOnTimeout (timers.js:288:5)
at listOnTimeout (timers.js:251:5)
at Timer.processTimers (timers.js:211:10)
(node:13096) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1)
(node:13096) [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.
The log clearly shows that your node server is unable to connect to MongoDB. The reasons might be any. Let me list down a few possibilities.
MongoDB Server is down. You might have to restart the same
You node server might be behind some firewall which doesn't allow DB connection to external DBs.
You can check the connection from shell using:
mongod "mongodb_host_url"

I was trying to build a API with node.js, express and mongodb. After installing nodemon mongodb went wrong

It seems like the mongodb server connection went wrong but I was not able to figure out how to fix the problem. Can someone went through the same issue please help me out? Thank you so much!
Error messages in terminal are as follows:
(node:63820) UnhandledPromiseRejectionWarning: MongoNetworkError: failed to connect to server [localhost:27017] on first connect [MongoNetworkError: connect ECONNREFUSED 127.0.0.1:27017]
at Pool.<anonymous> (/Users/Harry/Documents/code/testAPI/node_modules/mongodb-core/lib/topologies/server.js:503:11)
at Pool.emit (events.js:127:13)
at Connection.<anonymous> (/Users/Harry/Documents/code/testAPI/node_modules/mongodb-core/lib/connection/pool.js:326:12)
at Object.onceWrapper (events.js:219:13)
at Connection.emit (events.js:127:13)
at Socket.<anonymous> (/Users/Harry/Documents/code/testAPI/node_modules/mongodb-core/lib/connection/connection.js:245:50)
at Object.onceWrapper (events.js:219:13)
at Socket.emit (events.js:127:13)
at emitErrorNT (internal/streams/destroy.js:64:8)
at process._tickCallback (internal/process/next_tick.js:152:19)
(node:63820) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1)
(node:63820) [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.
It seems there's no database instance running at localhost:27017. Be sure to start mongodb instance before running your code.
Depending on your OS, the process of starting mongodb daemon very, see https://docs.mongodb.com/manual/tutorial/manage-mongodb-processes/

Resources