Express server don't start when I use "mongoose.connect' - node.js

I'm doing an App with React, Express and MongoDB,
Everything is OK when I start the Express server with this line :
app.listen(port, () => console.log(`Server running on ${port}`));
But when I try to start the server with this :
mongoose
.connect(
`mongodb+srv://${process.env.USER}:${process.env.PASSWORD}#ofilms-demo-f9iwz.mongodb.net/${process.env.DB}`,
{ useNewUrlParser: true, useUnifiedTopology: true }
)
.then(() =>
console.log(
`Server running on ${port} and connection to MongoDB database is OK !`
)
)
.catch((err) => console.log(err));
I can't access to localhost:5000 (server port) and I have no error messages !
The env variables are OK, I logged them..

You're connecting to MongoDB but not actually starting the server (which are two separate things):
mongoose
.connect(
`mongodb+srv://${process.env.USER}:${process.env.PASSWORD}#ofilms-demo-f9iwz.mongodb.net/${process.env.DB}`,
{ useNewUrlParser: true, useUnifiedTopology: true }
)
.then(() =>
console.log(`Connection to MongoDB database is OK !`)
// Start the server here
app.listen(port, () => console.log(`Server running on ${port}`));
)
.catch((err) => console.log(err));

Related

i got a problem when im connecting to mongodb

Terminal
[nodemon] app crashed - waiting for file changes before starting...
[nodemon] restarting due to changes...
[nodemon] starting `node index.js`
(node:16036) [MONGOOSE] DeprecationWarning: Mongoose: the `strictQuery` option will be switched back to `false` by default in Mongoose 7. Use `mongoose.set('strictQuery', false);` if you want to prepare for this change. Or use `mongoose.set('strictQuery', true);` to suppress this warning.
(Use `node --trace-deprecation ...` to show where the warning was created)
server is running on 5000
db error
this is index.js
const express = require('express');
const app = express();
var mongoUrl ="mongodb://localhost:27017/TestDB"
const mongoose = require('mongoose');
mongoose.connect("mongodb://localhost:27017/TestDB", { useNewUrlParser: true, useUnifiedTopology: true }, (err) => {
if (!err) console.log('db connected');
else console.log('db error');
})
app.listen(5000, () => {
console.log('server is running on 5000');
});
mongoose
.connect(`mongodb+srv://DB_USER:DB_PASS#cluster0.mbv6h.mongodb.net/myFirstDatabase?retryWrites=true&w=majority`, {
useNewUrlParser: true,
useUnifiedTopology: true
})
.then(() => {
console.log('Database connection successful!');
}).catch(error){
console.log(error)
}
you can get the entire connection string from MongoDB and input your DB user and password
It seems that you are trying to connect to a local instance of MongoDB. I remember this caused me a few headaches.
Try making sure that you have it downloaded and running:
Open command prompt (on Windows) or terminal (on MacOS)
Type mongod and click enter
If you get a long response then you have it installed but it might not be running or running on the correct port.
If you get a response something like this: 'mongod' is not recognized as an internal or external command, operable program or batch file. then that means you don't have MongoDB installed https://www.mongodb.com/docs/manual/administration/install-community/ to find instructions on how to install it.
Also...
The code you are using would work but it's a little untidy.
Try:
const express = require("express")
const mongoose = require("mongoose")
const app = express()
// Define port and mongodb url once so you don't have to repeat yourself
const PORT = 3000
const MONGO = "mongodb://localhost:27017/TestDB"
// Add this line to get rid of the first error you got
mongoose.set("strictQuery", false)
mongoose
.connect(MONGO, { useNewUrlParser: true, useUnifiedTopology: true })
.then(() => console.log("Database connected!"))
.catch((err) => console.log(err))
app.listen(PORT, () => {
console.log("Server is running on port " + PORT)
})

Create mongoose connection behind the university proxy?

I am building A MERN stack app on linux. The internet only work when we use proxy server of college. I am using mongoose for creating connection with MongoDB Atlas. The issue is that mongoose is unable to connect to MongoDB although i already set the proxy. How can I create connection in mongoose through university proxy server with MongoDB Atlas.
Currently mongoose connection is setup like this:
const CONNECTION_URL =process.env.CLUSTER_URL;
const PORT = process.env.PORT || 3000;
mongoose
.connect(CONNECTION_URL, { useNewUrlParser: true, useUnifiedTopology: true })
.then(() =>
app.listen(PORT, () => {
console.log(`server running at PORT ${PORT}`);
}),
)
.catch(error => console.log(error));
Currently university is using HTTP_PROXY=http://172.16.100.7:3022.

Can't connect to MongoDB through heroku but works on localhost

Trying to push my simple notes app to heroku but when launched on heroku mongoDB gives me this error
Could not connect to any servers in your MongoDB Atlas cluster.
My backend works perfectly fine while my app is running locally and I have whitelisted all IPs in mongoDB and added MONGODB_URI as a local var in heroku so I'm unsure what is wrong at this point.
Here is my connection.
const mongoose = require('mongoose')
const url = process.env.MONGODB_URI
console.log('Connecting to..', url)
mongoose.connect(url, { useNewUrlParser: true, useUnifiedTopology: true, useFindAndModify: false, useCreateIndex: true })
.then(result => {
console.log('Connected to MongoDB')
})
.catch((error) => {
console.log(`Error connecting to MongoDB: `, error.message)
})
Fixed the problem by deleting my whitelist in mongoDB Atlas and then adding it back, my server connected on heroku after that.

i am getting connection error on prod not localhost

I am trying to connect to cloud mongo db using mongoose with the connection string
const mongoose = require("mongoose");
mongoose.connect(
"mongodb+srv://<user>:<pass>#<cluster>/<db>?retryWrites=true&w=majority", {
useNewUrlParser: true,
useUnifiedTopology: true
}
).then(res => {
console.log("successful" + res);
})
.catch(err => {
console.log("connection error:", err);
})
module.exports = mongoose;
This works fine on my local machine but when I upload and run it on my production server it doesn't connect.
I have to set it to allow connections from all IPs and I have also add my server IP to it but still it shows me the same error

Application error after deploying to heroku

I've checked Procfile, package.json. Nothing seems to solve the problem.
My code for mongoose connection:
mongoose
.connect(process.env.uri, {
useNewUrlParser: true,
useUnifiedTopology: true,
useCreateIndex: true,
})
.then(() => {
console.log("DB connected");
})
.catch((err) => {
console.log(`DB connection error: ${err.message}`);
});
after heroku logs --tail
I had a similar problem, and I solved the issue by changing networking access to 'ALLOW ACCESS FROM ANYWHERE' on MongoDB.

Resources