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!");
});
Related
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
})
I am trying to connect MongoDB with my signup.js, but it's not connecting. I am unable to find the problem. How can I solve this?
Code of signup.js:
const express = require('express')
const app = express()
require("./db/mydb");
app.get('/', (req, res) => {
res.send('Hello World!')
})
app.listen(4000, () => {
console.log(`App listening on port 4000`)
})
Code of mydb.js:
const mongoose = require("mongoose");
mongoose.connect("mongodb://localhost:27017/mydata",{
useNewUrlParser:true,
useUnifiedTopology:true,
useCreateIndex:true
}).then(()=>{
console.log("connection successful")
}).catch((e)=>{
console.log("Not connected")
})
Error:
App listening on port 4000
Not connected
If the last log statement is replaced with console.log(e), the output is:
MongoParseError: option usecreateindex is not supported
Here you have a simple example of how to connect MongoDB to Node.js using Express.js and Mongoose on localhost obviously:
File server.js
const express = require("express");
const mongoose = require("mongoose");
const app = express();
const port = 3000;
app.get("/", (req, res) => {
res.send("Express and Mongoose connection!");
});
// Connect to db
mongoose
.connect("mongodb://localhost:27017/test")
.then(() => {
// Listen for requests
app.listen(port, () => {
console.log(
`Connected to DB & Server is listening at http://127.0.0.1:${port}`
);
});
})
.catch((error) => {
console.log(error);
});
And as we can read in the Mongoose documentation → no more deprecation warning options
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.
It was tested with: "express": "^4.18.1", "mongoose": "^6.6.5"
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?
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;
I'm having this issue on how can I connect my socket.io to my existing mongodb connection? Currently now I'm creating a task management app. I'm planning to add a chat features to my app. But I'm having this issue on how can connect this to my existing mongodb connection.
server.js
import express from 'express';
import cors from 'cors';
import http from 'http';
import { Server } from 'socket.io';
import path from 'path';
import connect from './dbconnect.js';
import accountRoutes from './routes/accountRoutes.js';
const app = express();
app.use(cors());
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
app.use('/api/user', accountRoutes);
const __dirname = path.resolve('..');
app.use('/public/uploads', express.static(__dirname + '/public/uploads/'));
const chatServer = http.createServer(app);
const PORT = process.env.PORT || 5000;
const socket = new Server(chatServer);
socket.on('connection', (socket) => {
console.log('a user connected');
});
**Connection from my existing mongodb database**
connect
.then(() => {
app.listen(PORT, () =>
console.log(`Server Running on Port: http://localhost:${PORT}`)
);
})
.catch((error) => console.log(`${error} did not connect`));
dbconnect.js
import mongoose from 'mongoose';
import dotenv from 'dotenv';
dotenv.config();
const connect = mongoose.connect(process.env.CONNECTION_URL, {
useNewUrlParser: true,
useUnifiedTopology: true,
useCreateIndex: true,
});
export default connect;
This is how I setup my database connection,
db.connect.js
import mongoose = require('mongoose');
const options ={
user:`${config.mngusername}`,
pass:`${config.mngpassword}`,
keepAlive: true,
keepAliveInitialDelay: 300000,
useNewUrlParser: true,
useCreateIndex: true,
useUnifiedTopology: true
}
const MONGO_URI = `mongodb://${config.mongourl}:${config.mongoport}/${config.mongocollection}?authSource=admin`;
try {
mongoose.set('useFindAndModify', false);
mongoose.connect(MONGO_URI, options);
mongoose.connection.on('connected', ()=>{
console.log({status:true,msg:'Mongoose default connection open to ' + MONGO_URI},'service');
});
// If the connection throws an error
mongoose.connection.on('error', (err)=>{
console.log({status:false,msg:'handle mongo errored connections: ' + err},'service');
});
// When the connection is disconnected
mongoose.connection.on('disconnected', ()=>{
console.log({status:false,msg:'Mongoose default connection disconnected'},'service');
});
process.on('SIGINT', ()=>{
mongoose.connection.close(()=>{
console.log({status:false,msg:'App terminated, closing mongo connections'},'service');
process.exit(0);
});
});
} catch (error) {
console.log({status:false,msg:error},'service');
}
Then you would only import your DB script in your main script using :
require('locationofdbscript');
And start your socket io server normally without having the dependence on the DB connection.
The DB script will log if the connection was successful or not and it will also automatically retry failed connections.
Hope that works for you.