uri is returning undefined. Mongodb connection is not been established - node.js

enter image description here I need to know what's the problem. I am not getting the message on console for establishment of Mongodb database connection.
Here is a link to the error picture. https://drive.google.com/file/d/14cdAgAjfVX6R7pXND-FbjbK_3r-A3F-J/view?usp=share_link
server.js file
const express = require('express');
const cors = require('cors');
const mongoose = require('mongoose');
require('dotenv').config();
const app = express();
const port = process.env.port || 5000;
app.use(cors());
app.use(express.json());
// debugger
var uri; // Define outside
if(process.env.ATLAS_URI){
uri = process.env.ATLAS_URI; // Assign inside the block
}
mongoose.connect(uri, { useNewUrlParser: true, useCreateIndex: true}
);
const connection = mongoose.connection;
connection.once('open', () => {
console.log("MongoDB database connection established successfully");
})
const exercisesRouter = require('./routes/exercises');
const usersRouter = require('./routes/users');
app.use('/exercises', exercisesRouter);
app.use('/users', usersRouter);
app.listen(port, ()=> {
console.log(`Server is running on port: ${port}`);
});
.env file
ATLAS_URI = mongodb+srv://tripsy25:Mongo#123#cluster0.lwpkrde.mongodb.net/?retryWrites=true&w=majority
I tried to debug the code and found that uri was coming as undefined. Do I need to convert the password in ATLAS_URI to some other format?

The .env file must be located in the root folder of your project. And you should run the project from the root folder. Therefore:
Example 1
server.js
.env
Run it with node ./server.js
Example 2
src
|-server.js
.env
Run it with node ./src/server.js

You did one mistake in .env file
you did
ATLAS_URI = mongodb+srv://tripsy25:Mongo#123#cluster0.lwpkrde.mongodb.net/?retryWrites=true&w=majority
But you have to use url of atlas as an string
ATLAS_URI = "mongodb+srv://tripsy25:Mongo#123#cluster0.lwpkrde.mongodb.net/?retryWrites=true&w=majority"

The .env file must be located on the root folder and you must include it in the file where ever you need it at the very top.
and a few changings you just need to do and the things are good to go.
require('dotenv').config();
const express = require('express');
const cors = require('cors');
const mongoose = require('mongoose');
mongoose.set('useNewUrlParser', true);
mongoose.set('useFindAndModify', false);
mongoose.set('useCreateIndex', true);
mongoose.set('useUnifiedTopology', true);
const app = express();
const port = process.env.port || 5000;
app.use(cors());
app.use(express.json());
mongoose.connect(process.env.ATLAS_URI)
.then(() => {
console.log("DB connection successful")
app.listen(port, () => {
console.log(`app listening on port ${port}`);
})
})
.catch((err) => {
console.log(err)
})
const exercisesRouter = require('./routes/exercises');
const usersRouter = require('./routes/users');
app.use('/exercises', exercisesRouter);
app.use('/users', usersRouter);
I am not getting why you just create a var for ATLAS_URI. Just keep the code simple and neat and clean.

Related

heroku connecting to mongodb atlas only when node conected and running on vsCode

I create a web site with MERN stack and deploy it with heroku. the DB connected to mongodb atlas. work great locali but when i try to connect the DB with heroku its working only when my backend on vsCode connected to the DB.
the error notes is:
*Failed to load resource: net::ERR_CONNECTION_REFUSED
*Uncaught (in promise) Error: Network Error
at e.exports (createError.js:16:15)
at XMLHttpRequest.g.onerror (xhr.js:117:14)
this is my code:
const express = require("express");
const app = express();
const mongoose = require("mongoose");
const morgan = require("morgan");
const cors = require("cors");
const usersRouter = require("./routes/usersRout");
const authRouter = require("./routes/auth");
const carsRouter = require("./routes/carsRout");
const bizRouter = require("./routes/bizRout");
mongoose
.connect(
process.env.MONGODB_URI ||
"mongodb+srv://reutudler:eJ53Guyvm7ySeMra#notodb.s9aba.mongodb.net/notodb?retryWrites=true&w=majority"
)
.then(() => {
console.log("connected to mongo");
})
.catch((err) => {
console.log("faild to connect to mongo server", err);
});
app.use(cors());
app.use(morgan("dev"));
app.use(express.json());
if (process.env.NODE_ENV === "production") {
app.use(express.static("noto-front/build"));
}
app.use("/api/users", usersRouter);
app.use("/api/auth", authRouter);
app.use("/api/cars", carsRouter);
app.use("/api/biz", bizRouter);
const PORT = process.env.PORT || 8080;
app.listen(PORT, () => {
console.log(`connected on port ${PORT}`);
});
my config vars on heroku:
MONGODB_URI - mongodb+srv://reutudler:eJ53Guyvm7ySeMra#notodb.s9aba.mongodb.net/notodb?retryWrites=true&w=majority
NODE_ENV - production
what am i doing wrong?

Express, Node Error - connectDB is not a Function

I am new to express and tyring to connect to mongoAtlas via Express and start the server. I am facing an error where I have no clue why is it coming. Can someone help me out?
db.js
const mongoose = require('mongoose');
const config = require('config');
const db = config.get('mongoURI');
const connectDB = async () => {
try {
await mongoose.connect(db);
console.log('MongoDB Connected...')
}
catch(err) {
console.log(err.message);
process.exit(1);
}
}
module.export = connectDB;
server.js
const express = require('express');
const connectDB = require('./config/db');
const app = express();
// Connect database
connectDB();
app.get('/', (req, res) => res.send('API Running...'));
const PORT = process.env.PORT || 5000;
app.listen(PORT, () => console.log(`Server started on port ${PORT}`));
Error:
You need to change
module.export = connectDB;
to
module.exports = connectDB;

Socket.io + node JS = Error during handshake: error code 500

I was working on Socket.io and node jS to develop a chat web app. It worked locally but I have faced many issues when I deployed my changes to Azure app service.
I am creating a secure connection on port 443. I have resolved other issues but I can't resolve this one.
This the error I'm getting in console on client side.
WebSocket connection to 'wss://mydomain/socket.io/?EIO=3&transport=websocket' failed: Error during WebSocket handshake: Unexpected response code: 500
This is how I'm connecting on server side
var socket = io.connect("https://mydomain:443", {transports: ['websocket'], secure: true, port: '443'});
and this is my server.js code:
const express = require("express");
const mongoose = require("mongoose");
const bodyParser = require("body-parser");
const passport = require("passport");
const users = require("./routes/api/users");
const base = require("./routes/api/base");
const leads = require("./routes/api/leads");
const requests = require("./routes/api/requests");
const offApp = require("./routes/api/offApp");
const chat = require("./routes/api/chat");
const chatSocket = require("./routes/socket/chat");
const path = require("path"); // on top
const app = express();
const cors = require('cors')
const https = require('https');
const fs = require('fs');
var options = {
pfx: fs.readFileSync('certificate.pfx'),
passphrase: 'password'
};
app.use(cors());
var server = https.createServer(options, app);
var client = require("socket.io").listen(server);
client.origins('*:*');
client.set('transports', ['websocket']);
server.listen(443);
// Bodyparser middleware
app.use(
bodyParser.urlencoded({
extended: false
})
);
app.use(bodyParser.json());
// DB Config
const db = require("./config/keys").mongoURI;
// Connect to MongoDB
mongoose
.connect(
db,
{ useNewUrlParser: true }, (err, db) => {
if (err) {
throw err;
}
console.log('MongoDB connected');
chatSocket(db, client);
});
// Passport middleware
app.use(passport.initialize());
// Passport config
require("./config/passport")(passport);
// Routes
app.use("/api/users", users);
app.use("/api/base", base);
app.use("/api/leads", leads);
app.use("/api/requests", requests);
app.use("/api/offapp", offApp);
app.use("/api/chat", chat);
const port = process.env.PORT || 5000;
app.use(express.static("client/build")); // change this if your dir structure is different
app.get("*", (req, res) => {
res.sendFile(path.resolve(__dirname, "client", "build", "index.html"));
});
app.listen(port, () => console.log(`Server up and running on port ${port} !`));
I have checked the logs, there are no errors there.

How to export models in the form of middle ware in main server.js and write routes for tables in separate model.js file

I am a newbie in node.I have created a server file to connect mongoDB and wrote routes in the same. Created a model.js for table attributes.I want to write a route for my other tables.
https://codingthesmartway.com/the-mern-stack-tutorial-building-a-react-crud-application-from-start-to-finish-part-2/
Taken reference from here. But want to create a seperate file for connection and add module for tables
This is my server.js
const express = require('express');
const app = express();
const bodyParser = require('body-parser');
const cors = require('cors');
const mongoose = require('mongoose');
const todoRoutes = express.Router();
const PORT = 4000;
let Todo = require('./todo.model');
app.use(cors());
app.use(bodyParser.json());
app.use('/todos', todoRoutes);
mongoose.connect('mongodb://127.0.0.1:27017/todos', {
useNewUrlParser: true });
const connection = mongoose.connection;
connection.once('open', function() {
console.log("MongoDB database connection established
successfully");
})
app.listen(PORT, function() {
console.log("Server is running on Port: " + PORT);
});
todoRoutes.route('/').get(function(req, res) {
Todo.find(function(err, todos) {
if (err) {
console.log(err);
} else {
res.json(todos);
}
});
});
this routes are in this file i want to export it from other model.js
If you want to put route in another file,i would suggest you to make a new folder route and then inside it make a new file by route name(say createUser.js).
In this server.js file only use
const express = require('express');
const app = express();
const bodyParser = require('body-parser');
const cors = require('cors');
const mongoose = require('mongoose');
const PORT = 4000;
let Todo = require('./todo.model');
app.use(cors());
app.use(bodyParser.json());
app.use('/todos', todoRoutes);
mongoose.connect('mongodb://127.0.0.1:27017/todos', {
useNewUrlParser: true });
const connection = mongoose.connection;
connection.once('open', function() {
console.log("MongoDB database connection established
successfully");
})
app.listen(PORT, function() {
console.log("Server is running on Port: " + PORT);
});
export default app;
And in another file inside route folder use the require imports and define the route here.
const todoRoutes = express.Router();
todoRoutes.route('/').get(function(req, res) {
Todo.find(function(err, todos) {
if (err) {
console.log(err);
} else {
res.json(todos);
}
});
});
module.exports=todoRoute;
Furthur you can import this route in any model.js and use it for implementation of logic.
Note-: You can also use a third folder controllers and implement the route logic there since it is the best practice to not write logic on route but use controller file for it.Also you can separate the DB connection login in another file.

Cannot GET , nodejs

I tired to solve this problem, when I browse localhost:5000 I got error like
Cannot GET /
//*****************app.js************
const express = require('express');
const mongoose = require('mongoose');
const logger = require('morgan');
const bodyParser = require('body-parser');
const app = express();
const v1 = require('./routes/v1');
// ************* DB Config *************//
mongoose.connect(process.env.MONGO_DB_URL, {
useNewUrlParser: true,
useCreateIndex: true
});
mongoose.connection.on('connected' , () => {
console.log('Connected to the databse');
});
mongoose.connection.on('error' , (err) => {
console.error('Failed to connected to the databse: ${err}');
});
//**************Midlewares ***********//
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended : true}));
//*************Routes *****************//
app.use('/api/v1', v1);
module.exports = app ;
//********** index.js ***************//
require('dotenv').config();
const app = require('./src/app')
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
console.log('Server is ready for connections on port ${PORT}');
});
the problem here is you have no route at the root /
you have to add either your routes you defined or define a root route

Resources