MongoParseError: mongodb+srv URI cannot have port number - node.js

i have the following code
database.js file
const mongoose = require('mongoose');
const { MONGO_URI } = process.env;
exports.connect = () => {
// lets connect our database
mongoose.connect(MONGO_URI, {
useNewUrlParser: true,
useUnifiedTopology: true,
useCreateIndex: true,
useFindAndModify: false,
}).then(() =>{
console.log('connected to the database')
}).catch((error) =>{
console.log('connection to the database failed');
console.error(error);
process.exit(1);
});
};
index.js file
const http = require('http');
const app = require('./app');
const server = http.createServer(app);
const { API_PORT } = process.env;
const port = process.env.PORT || API_PORT;
server.listen(port, () => {
console.log(`server is running on port ${port}`)
})
when i run my index.js file i get an error
server is running on port 4001
connection to the database failed
MongoParseError: mongodb+srv URI cannot have port number
My .env file (note:password and name is made up)
API_PORT=4001
MONGO_URI=mongodb+srv://dwin:#12345#cluster0.3qohzms.mongodb.net/?retryWrites=true&w=majority
what coulb be wrong with the above code?

Related

how to connect mongodb

Im not sure how to get my mongodb connected and I keep getting this error what should I change?
server#1.0.0 start
> node --experimental-modules --es-module-specifier-resolution=node index.js
MongooseError: The `uri` parameter to `openUri()` must be a string, got "undefined". Make sure the first parameter to `mongoose.connect()` or `mongoose.createConnection()` is a string. Failed to connect database
Listening on PORT 5000
my index.js file:
import express from "express";
import mongoose from "mongoose";
import cors from "cors";
import dotenv from "dotenv";
// Importing the routes
import authRoute from "./routes/authRoute";
const app = express();
dotenv.config({ path: "./config.env" });
app.use(cors());
app.use(express.json());
// All the routes
app.use("/api", authRoute);
mongoose.connect(process.env.DATABASE, {
useNewUrlParser: true,
useUnifiedTopology: true,
}).then(() => {
console.log("Database connected successfully");
})
.catch((err) => {
console.log(`${err} Failed to connect database`);
});
const PORT = process.env.PORT || 5000;
// Listening to port
app.listen(PORT, () => {
console.log(`Listening on PORT ${PORT}`);
});
You can use this:
const mongoose = require("mongoose");
mongoose.connect(
process.env.MONGO_URI, {
useNewUrlParser: true,
useUnifiedTopology: true,
});
mongoose.connection.on("error", (err) => {
console.log("err", err);
});
mongoose.connection.on("connected", (err, res) => {
console.log("MongoDB connected successfully!");
});

how to use async and await to connect to mongoDB database?

I am new to JavaScript and currently learning mongoDB with node.
The code Bellow is in callback functions but i want to connect to mongoDB database using async and await with try and catch .
const mongoose = require("mongoose");
mongoose.connect("mongodb://localhost/selfdb");
mongoose.connection
.once("open", () => {
console.log("connection has been made!");
})
.on("error", (error) => {
console.log("connection error:", error);
});
I tried doing this way:
const mongoose = require("mongoose");
async function main() {
const uri = "mongodb://localhost/selfdb";
const client = new mongoose(uri);
try {
await client.connect();
console.log("connection has been made!");
} catch (e) {
client.error(e);
} finally {
await client.close();
}
}
main().catch(console.error);
but i got following error:
TypeError: mongoose is not a constructor
how could i do it the right way?
am i doing any silly mistake?
I believe the better way to connect is like this
const mongoose = require('mongoose')
const connectDB = async () => {
try {
const conn = await mongoose.connect(process.env.MONGO_URI)
console.log(`MongoDB Connected: ${conn.connection.host}`)
}
catch (error) {
console.log(error)
process.exit(1)
}
}
module.exports = connectDB
Mongo URI is in .env file, but you can replace it with your connection string (but more secure in .env file)
Then in server.js or index.js (entry file)
const connectDB = require('path_to_file')
connectDB()
I Tried this approach !! May be it could be helpful.
DBconn.js (MONGO_URL is from .env file & dev_db_url is optional here)
require('dotenv').config({ path: 'env/.env' });
const dev_db_url = 'local dev. db url is not defined.';
const mongoDB_URL = process.env.MONGO_URL || dev_db_url;
const dbOptions = {useNewUrlParser: true, useUnifiedTopology: true};
const connectDB = async (cb) => {
try {
await mongoose.connect(mongoDB_URL, dbOptions)
.then(() => {
cb();
console.log("Connected to Database");
})
} catch (error) {
console.error("Could not Connect to Database", error)
}
};
module.exports = connectDB;
Server.js (Server will start to listen only after successful DB Connect)
require('dotenv').config({ path: 'env/.env' });
const connectDB = require('./database/DBConn')
const port = process.env.PORT || 5000;
const express = require('express')
const app = express()
// Connecting to DB
connectDB(()=>{
app.listen(port, () => {
console.log(`Backend : NodeJS/express server started on http://localhost:${port}`)
})
});
Another Way :
DBconn.js
const mongoose = require("mongoose");
require('dotenv').config({ path: 'env/.env' });
const dev_db_url = 'local dev. db url is not defined.';
const mongoDB_URL = process.env.MONGO_URL || dev_db_url;
const dbOptions = {useNewUrlParser: true, useUnifiedTopology: true};
const connectDB = async () => {
try {
await mongoose.connect(mongoDB_URL, dbOptions);
} catch (error) {
console.error("Could not Connect to Database", error)
}
};
module.exports = connectDB;
Server.js (here we use .once method)
require('dotenv').config({ path: 'env/.env' });
const mongoose = require("mongoose");
const connectDB = require('./database/DBConn')
const port = process.env.PORT || 5000;
const express = require('express');
const app = express();
connectDB();
mongoose.connection.once('open', () => {
console.log('Connected to MongoDB');
app.listen(port, () => {
console.log(`Backend : NodeJS/express server started on http://localhost:${port}`)
})
});

Postman: Connect ECONNREFUSED 127.0.0.1:5005

I have developed an API endpoint. It was working fine before. Unfortunately the project folder got corrupted (I recreated the files db.js and server.js). But now when I try to fetch data from API, I'm getting:
"connect ECONNREFUSED 127.0.0.1:5005"
The URL I'm using is localhost:
And my server is running on the same port i.e. 5005:
Can someone please elaborate what can be the problem? My hunch is that when I recreated the files I may have missed something:
db.js:
const mongoose = require('mongoose');
const userName = "myUsername"
const password = "myPassword"
const dbName = "comfyRooms"
const dbURL = `mongodb+srv://${userName}:${password}#mongo-cluster.damzf.mongodb.net/${dbName}?authSource=admin&replicaSet=atlas-s7z01e-shard-0&readPreference=primary&appname=MongoDB%20Compass&ssl=true`
mongoose.connect(dbURL, {useUnifiedTopology: true, useNewUrlParser: true})
let connection = mongoose.connection
connection.on('error', () => {
console.log('Unable to connect to MongoDB')
})
connection.on('connected', () => {
console.log("MongoDB connection established :)")
})
module.exports = mongoose
server.js
const express = require('express')
const app = express()
const dbConfig = require('./db')
const roomsRoute = require('./routes/roomsRoute')
app.use('/api/rooms', roomsRoute)
const port = process.env.PORT || 5005
app.listen(() => {
console.log("Node JS server listening on port " + port)
})
roomsRoute.js:
const express = require('express');
const router = express.Router();
const Room = require('../models/rooms');
router.get('/getallrooms', async (req, res) => {
try {
const rooms = await Room.find({});
return res.send(rooms);
} catch (error) {
return res.status(400).json({message: error});
}
});
module.exports = router;
I have attached the important files. Please let me know if any other information is missing. Thanks!
You are not passing the port variable to the listen function, you are just logging it
app.listen(() => {
console.log("Node JS server listening on port " + port)
})
This should work
app.listen(port, () => {
console.log("Node JS server listening on port " + port)
})

Node.js app cannot connect to MongoDB Atlas cluster

error:
server running in development mode on port 5000
errorMongoParseError: option usecreateindex is not supported
[nodemon] app crashed - waiting for file changes before starting...
db.js
const connectDB = async () => {
try {
const conn = await mongoose.connect(process.env.MONGO_URI, {
useUnifiedTopology: true,
useNewUrlParser: true,
useCreateIndex: true,
});
console.log(`MongoDB connected :${conn.connection.host}`);
} catch (error) {
console.error(`error${error}`);
process.exit(1);
}
};
export default connectDB;
server.js
import express from "express";
import dotenv from "dotenv";
import connectDB from './config/db.js'
import products from './data/products.js'
dotenv.config();
connectDB()
const app = express();
app.get("/", (req, res) => {
res.send("api is running... ");
});
app.get("/api/products", (req, res) => {
res.json(products);
});
app.get("/api/products/:id", (req, res) => {
const product = products.find(p => p._id === req.params.id);
res.json(product);
});
const PORT = process.env.PORT || 5000
app.listen(PORT, console.log(`server running in ${process.env.NODE_ENV} mode on port ${PORT}`));
No More Deprecation Warning Options
Mongoose docs
useNewUrlParser, useUnifiedTopology, useFindAndModify, and
useCreateIndex are no longer supported options. Mongoose 6 always
behaves as if useNewUrlParser, useUnifiedTopology, and useCreateIndex
are true, and useFindAndModify is false. Please remove these options
from your code.
db.js
const connectDB = async () => {
try {
const conn = await mongoose.connect(process.env.MONGO_URI, {
// useUnifiedTopology: true, <-- no longer necessary
// useNewUrlParser: true, <-- no longer necessary
// useCreateIndex: true, <-- no longer necessary
});
console.log(`MongoDB connected :${conn.connection.host}`);
} catch (error) {
console.error(`error${error}`);
process.exit(1);
}
};
export default connectDB;

How to connect react-native to peerjs server on heroku

how to use PeerServer deployed on heroku, in react native
I watched a youtube tutorial where tutor connected his react-native app with peerserver on localhost:5000 and that worked. However, my peerserver is deployed on heroku, trying to connect my app to it the same way the tutor did isn't working. I get the error [Error: Could not get an ID from the server.] which comes from peerServer.on('error', console.log)
This is my react-native code
export const API_URI = 'https://mvmserver.herokuapp.com'
// Peer Config
const peerServer = new Peer(undefined, {
host: 'mvmserver.herokuapp.com',
secure: false,
port: 52129,
path: '/mypeer'
})
peerServer.on('error', console.log)
// Socket config
export const socket = IO(`${API_URI}`, {
forceNew: true
})
socket.on('connection', () => console.log('Connected client'))
This is how the tutor had his
export const API_URI = 'localhost:5000'
// Peer Config
const peerServer = new Peer(undefined, {
host: '192.00.0.0.0',
secure: false,
port: 5000,
path: '/mypeer'
})
peerServer.on('error', console.log)
// Socket config
export const socket = IO(`${API_URI}`, {
forceNew: true
})
socket.on('connection', () => console.log('Connected client'))
My peerserver.js on heroku
const express = require('express')
const http = require('http')
const socketio = require('socket.io')
const {ExpressPeerServer} = require('peer');
const app = express();
const server = http.createServer(app)
const io = socketio(server).sockets
//Borderparser
app.use(express.json())
const customGenerationFunction = () => (Math.random().toString(36) + "0000000000000000000").substr(2, 16)
const peerServer = ExpressPeerServer(server, {
debug: true,
path: '/',
genderateClientId: customGenerationFunction
})
app.use("/mypeer", peerServer)
io.on('connection', function(socket) {
console.log('connected')
socke.on('join-room', ({roomID, userId}) => {
socket.join(roomID)
socket.to(roomID).broadcast.emit('user-connected', userId)
})
})
const port = process.env.PORT || 5000
server.listen(port, () => console.log(`Server is running on port ${port}`))

Resources