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
Related
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.
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.
I recently began using google cloud and I wanted to host my Postgres database to google cloud and deployed my node js application to app engine however I am having issues connecting my nodejs app to the hosted database,
I have already enabled the Cloud SQL API.
I use node-postgres here is my connection object:
const { Pool } = require("pg");
const pool = new Pool({
user: process.env.DB_USER,
password: process.env.DB_PASS,
port: 5432,
host: `/cloudsql/${process.env.CLOUD_SQL_CONNECTION_NAME}`,
database: process.env.DB_NAME,
});
module.exports = pool;
This is the query:
router.get("/", async (req, res) => {
try {
const { rows } = db.query("SELECT * FROM users ORDER BY id DESC");
res.json(rows);
} catch (err) {
console.error(err);
}
});
this is my app.yaml:
runtime: nodejs14
env_variables:
DB_USER: postgres
DB_PASS: password here
DB_NAME: the db name here
CLOUD_SQL_CONNECTION_NAME: my connection name here
beta_settings:
cloud_sql_instances: my connection name here
when I run this I get an ENONET error:
UnhandledPromiseRejectionWarning: Error: connect ENOENT /cloudsql/instance_id/.s.PGSQL.5432
at PipeConnectWrap.afterConnect [as oncomplete] (net.js:1146:16)
(Use `node --trace-warnings ...` to show where the warning was created)
(node:121478) 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:121478) [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.
I am not sure what exactly happened, I followed the official documentation but it still didnt succeed.
I think that your problem is that in your connection object, the field "host" expects an IP address and it looks like you're putting in the UNIX socket name mentioned in some pages of the documentation. Try to put in the valid public or private IP address of your Cloud SQL instance instead as that's what the library you're using expects in this case.
Also, make sure that you configure your App Engine correctly in each case(public or private IP) like in this documentation page
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!
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"