I've integrated MongoDB atlas to my nodejs application, but the connection keeps dropping every few hours, which is forcing the app to restart. Is there a away to handle reconnections in the code to avoid restart of the app ?
{ MongoNetworkError: connection 2 to 67.156.445.93:27017 closed
at (anonymous function).forEach.op (/home/ubuntu/app/node_modules/mongodb/lib/cmap/connection.js:63:15)
at Map.forEach ()
at TLSSocket.Connection.stream.on (/home/ubuntu/app/node_modules/mongodb/lib/cmap/connection.js:62:20)
at TLSSocket.emit (events.js:203:15)
at _handle.close (net.js:607:12)
at TCP.done (_tls_wrap.js:388:7)
name: 'MongoNetworkError',
[Symbol(mongoErrorContextSymbol)]: { isGetMore: true } }
Code:
const log = console.log;
const mongoose = require('mongoose');
const link = ' URL of MONGOATLAS DB';
const connectDB = async () => {
mongoose.connect(link, {
useNewUrlParser: true,
useUnifiedTopology: true
});
mongoose.connection.on('connected',() => {
log(`MongoDB connection successful!`);
});
mongoose.connection.on('error',(err) => {
log(`MongoDB connection error => ${err}!`);
});
mongoose.connection.on('disconnected', () => {
log(`MongoDB connection diconnected`);
});
}
module.exports = connectDB;
Have a file called database.js. Inside it, put this code:
const mongoose = require("mongoose");
const db = "mongodb://localhost:27017/yourDbName" //Or use atlas url.
const connectDB = async () => {
try {
await mongoose.connect(db, {
useNewUrlParser: true,
useUnifiedTopology: true,
useCreateIndex: true,
useFindAndModify: false
});
console.log("Mongo db Connected !");
} catch (err) {
console.log(err.message);
//exit process with failure
process.exit(1);
}
};
module.exports = connectDB;
In your server.js or index.js:
const connectDB = require("./database.js");
Related
How do i fix this error i am not using MongoDb Atalas i want to use it in my local machine
const express = require('express');
const app = express()
const mongoose = require('mongoose');
const url = 'mongodb://localhost:27017/testDb'
mongoose.connect(url, {useNewUrlParser: true, useUnifiedTopology: true})
.then(() => console.log('DB Connected'))
mongoose.connection.on('error', err => {
console.log(`DB connection error: ${err.message}`)
});
const NewSchema = new mongoose.Schema({
name:String,
age:Number
})
const newModel = new mongoose.model("collection",NewSchema)
const data = newModel({
name:"prajwal",
age:30
})
data.save()
app.listen(3000,()=>{
console.log("listening to the port 3000")
})
This is the error that i got from the code
The save() call should be awaited. Also, looks like you are not connected to the DB, try with:
const express = require('express');
const app = express();
const mongoose = require('mongoose');
const url = 'mongodb://localhost:27017/testDb';
const NewSchema = new mongoose.Schema({
name: String,
age: Number,
});
const newModel = new mongoose.model('collection', NewSchema);
(async () => {
try {
await mongoose.connect(url, {
useNewUrlParser: true,
useUnifiedTopology: true,
});
console.log('DB Connected');
const data = newModel({
name: 'prajwal',
age: 30,
});
await data.save();
} catch (err) {
console.log(`DB connection error: ${err.message}`);
}
})();
app.listen(3000, () => {
console.log('listening to the port 3000');
});
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 will be very grateful if you could help me with this issue. Although there are many similar problems, I couldn't find a solution about mine.
Everything is okay, when I'm starting the app- it is connected to the port and the database, but then when I'm using a test post request from insomnia with the url http://localhost:3001/api/testRouter/test
and body {
"testText": "Art",
"testNumber": 1
}. I want a new test to be created and sent to the mongodb atlas, but I'm getting this error:
MongooseError: Operation tests.findOne() buffering timed out after 10000ms
at Timeout. (C:\Users\gabri\OneDrive\Desktop\ip-first\ip-first\server\node_modules\mongoose\lib\drivers\node-mongodb-native\collection.js:198:23)
at listOnTimeout (internal/timers.js:551:17)
at processTimers (internal/timers.js:494:7)
This is my db.js file, where I create connection with mongoose:
const mongoose = require('mongoose')
const dotenv = require('dotenv')
dotenv.config()
const connectDB= async()=>
{
try
{
await mongoose.connect(process.env.DATABASE_ACCESS,
{
useNewUrlParser: true,
useUnifiedTopology: true,
useCreateIndex: true
},
()=>
{
console.log("Database connected")
})
}
catch(err)
{
console.log("Error in db connection", err)
}
}
module.exports=connectDB;
This is my test model, which I'm using for testing:
const mongoose = require('mongoose')
const TestSchema = new mongoose.Schema({
testNumber:
{
type:Number,
required: true
},
testText:
{
type: String,
required: true,
trim: true
}
})
const Test = mongoose.model('Test', TestSchema);
module.exports=Test;
This is my test controller, which I'm using it for testing as well:
const Test = require('../models/Test')
exports.testControllerCreate =async(req,res)=>
{
console.log("in router") // it is printed on the console
console.log("body" , req.body) // it is printed on the console
const {testText, testNumber} = req.body;
console.log("check testText", testText) //it is printed on the console
console.log("check testNumber", testNumber) //it is printed on the console
try{
let test= new Test();
test.testText=testText;
test.testNumber=testNumber;
const existingTest = await Test.findOne({testText: testText})
if(existingTest)
{
return res.status(401).json({errorMessage: "Test already exists"})
}
await test.save();
res.status(200).json({successMessage: `Test successfully ${test} created`})
}
catch(err)
{
console.log("err", err)
res.status(500).json({errorMessage: 'Server error'})
}
}
These are my routes:
const express = require('express')
const router=express.Router()
const {testControllerCreate} = require('../controllers/testController')
console.log("router")
router.post('/test', testControllerCreate)
module.exports=router;
And this is my index.js file
const express=require('express')
const app=express()
const cookieParser=require('cookie-parser')
const cors=require('cors')
const connectDB=require('./database/db')
const testRouter = require('./routes/testRoute')
const { connect } = require('./routes/testRoute')
//middlewares
app.use(cors())
app.use(express.json())
app.use(cookieParser())
app.use("/api/testRouter", testRouter)
connectDB();
app.listen(3001, ()=>
{
console.log("running on port 3001 new try")
})
I really hope that someone could help me. I've tried changing the ips in the network access section in the mongodb atlas, checked my url if the password and the username are the same as these from the mongodb atlas, I tried using some extra async await methods, but nothing helped.
This is code for connection but I get error message everytime. I have included the mongoURI in default.json file but I am unable to detect the main problem here
const mongoose = require('mongoose');
const config = require('config');
const db = config.get('mongoURI');
const connectDB = async () => {
try {
await mongoose.connect(db, {
useNewUrlParser: true,
useUnifiedTopology: true
});
console.log('Mongodb connected ....');
} catch (err) {
console.log('error message');
process.exit(1);
}
}
I do not really know why I keep getting this error "Error: querySrv ECONNREFUSED _mongodb._tcp.cluster0-9esxx.gcp.mongodb.net" when I try to run my node app. Is it from the server or because of a poor internet?
This is the database.js file
const mongoose = require("mongoose");
const connectDB = async () => {
try {
const conn = await mongoose.connect(process.env.MONGO_URI, {
// to avoid warnings in the console
useNewUrlParser: true,
useUnifiedTopology: true,
useFindAndModify: false,
});
console.log(`mongoDB connected ${conn.connection.host}`);
} catch (err) {
console.error(err);
// stop the process
process.exit(1);
}
};
module.exports = connectDB;