Node.js app cannot connect to MongoDB Atlas cluster - node.js

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;

Related

TypeError: connectionString.startsWith is not a function

When I try to connect to the MongoDB this error happens. I have installed MongoDB in my package.json and all the other models but when I run the code it's connect to the port perfectly but as soon as I try to insert a collection the error happens “undertOne() is not defined”.
Moviedb.js
import app from './server.js';
import ReviewsDAO from "./dao/reviewsDAO.js";
import mongodb from 'mongodb';
import dotenv from 'dotenv';
const MongoClient=mongodb.MongoClient
//Load the environment variables from the .env file
dotenv.config();
//Access the environment variables
const mongo_username = process.env.MONGO_USERNAME;
const mongo_password = process.env.MONGO_PASSWORD;
//access to the db
const uri = new MongoClient(`mongodb+srv://${mongo_username}:${mongo_password}#cluster0.b5f7prn.mongodb.net/test`);
const port=4444;
MongoClient.connect(
uri,
{
maxPoolSize: 50,
wtimeoutMS: 2500,
useNewUrlParser: true
})
.catch(err => {
console.error(err.stack)
console.error("Error connecting to the database:", err.message)
process.exit(1)
})
.then(async client => {
await ReviewsDAO.injectDB(client)
app.listen(port, () => {
console.log(`listening on port ${port}`)
})
})
Server.js:
import express from 'express';
import cors from 'cors';
import reviews from './api/reviews.route.js';
//creating web server
const app = express();
app.use(cors());
app.use(express.json());
app.use('/api/v1/reviews', reviews);
app.use('*', (req,res)=>res.status(404).json({error:"Not found"}));
//to listen to the router
app.listen( 4444, () => {
console.log(`Listening on port 4444`);
});
export default app;
I have tried debugging the code the error appears in moviedb.js in this section:
MongoClient.connect(
uri,
{
maxPoolSize: 50,
wtimeoutMS: 2500,
useNewUrlParser: true
})
.catch(err => {
console.error(err.stack)
console.error("Error connecting to the database:", err.message)
process.exit(1)
})
.then(async client => {
await ReviewsDAO.injectDB(client)
app.listen(port, () => {
console.log(`listening on port ${port}`)
})
})
reviews.route.js:
import express from 'express';
import ReviewsCtrl from "./reviews.controller.js";
const router=express.Router();
router.route("/movie/:id").get(ReviewsCtrl.apiGetReviews);
router.route("/new").post(ReviewsCtrl.apiPostReview);
router.route("/:id")
.get(ReviewsCtrl.apiGetReviews)
.put(ReviewsCtrl.apiUpdateReview)
.delete(ReviewsCtrl.apiDeleteReview)
export default router;
You are passing a MongoClient instance as a uri to MongoClient.connect, which is wrong. Use this instead
MongoClient.connect(`mongodb+srv://${mongo_username}:${mongo_password}#cluster0.b5f7prn.mongodb.net/test`,
{
maxPoolSize: 50,
wtimeoutMS: 2500,
useNewUrlParser: true
})

MongoParseError: mongodb+srv URI cannot have port number

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?

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!");
});

app.post connection and middleware in nodejs

app.post is not working on postman and showing result in not in JSON format and also middleware is showing error in postman what m doing wrong in this??
is there any new middleware code introduced recently??
// importing
import express from "express";
import mongoose from "mongoose";
import Messages from "./dbMessages.js";
//app config
const app = express();
const port = process.env.PORT || 9000;
//middleware
app.use(express.json());
//DB config
const connection_url =
"mongodb+srv://admin:0ZKon3XRmT0SWkal#cluster0.7pljv.mongodb.net/whatsappdb?retryWrites=true&w=majority";
mongoose.connect(connection_url, {
// useCreateIndex: true,
// useNewUrlParser: true,
// useUnifiedTopology: true,
});
//????
//api routes
app.get("/", (req, res) => res.status(200).send("hello world"));
app.post("/messages/new", (req, res) => {
const dbMessage = req.body;
Messages.create(dbMessage, (err, data) => {
if (err) {
res.status(500).send(err);
} else {
res.status(201).send(data);
}
});
});
//listen
app.listen(port, () => console.log(`Listening on localhost:${port}`));
dbmessages.js is given below
import mongoose from "mongoose";
const whatsappSchema = mongoose.Schema({
message: String,
name: String,
timestamp: String,
received: Boolean,
});
export default mongoose.model("messageContent", whatsappSchema);
You are not creating the instance of a model.
app.post("/messages/new", (req, res) => {
const dbMessage = req.body,
messageModel = new Messages();
message.Modelmessage = req.body.Modelmessage;
message.Modelname = req.body.Modelname;
messageModel.timestamp = req.body.timestamp;
messageModel.received = req.body.received;
messageModel.save().then(data => {
res.status(201).send(data);
}).catch((e) => {
res.status(500).send(err);
})
});

connectDB is not a function

Hi I'm new to coding currently trying to set up a connection to my server.
Getting an error message:
"TypeError: connectDB is not a function"
This is my db.js file
const mongoose = require('mongoose')
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.message}`)
process.exit(1)
}
}
module.exports = { connectDB }
and this is my server.js file
const express = require('express')
const dotenv = require('dotenv')
const connectDB = require('./config/db')
const products = require('./seed/products')
dotenv.config()
connectDB()
const app = express()
server.get('/', (req, res) => {
res.send('API is running.........')
})
server.get('/api/products', (req, res) => {
res.json(products)
})
server.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
server.listen(
PORT,
console.log(`Server running in ${process.env.NODE_ENV} port ${PORT}`)
)
Looking for some assistance I'm really new to coding so please forgive me if I posted wrongly.
check this out:
You are exporting mongoose from the db.js file. Try exporting the function connectDB you just created.
// between brackets just in case you need to export something else, ok?
module.exports = { connectDB }
Then import it like this:
const { connectDB } = require('./config/db')
const mongoose = require('mongoose')
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.message}`)
process.exit(1)
}
}
module.exports = { connectDB }
const express = require('express')
const server = express()
const dotenv = require('dotenv')
const { connectDB } = require('./config/db')
const products = require('./seed/products')
dotenv.config()
connectDB()
const app = express()
server.get('/', (req, res) => {
res.send('API is running.........')
})
server.get('/api/products', (req, res) => {
res.json(products)
})
server.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
server.listen(
PORT,
console.log(`Server running in ${process.env.NODE_ENV} port ${PORT}`)
)

Resources