The mongoose.connect function gives error message - node.js

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

Related

client doesn't close that causes connection error `Topology is closed`

I use following code to connect to mongodb
conn.js
'use strict'
const { MongoClient } = require('mongodb');
const dbconfig = require('../config/index');
const client = new MongoClient(dbconfig.product.dbUrl, { useNewUrlParser: true });
client.connect(function (err) {
if (err) {
console.log(err);
} else {
console.log('mongodb connected');
}
});
const db = client.db(dbconfig.product.dbName);
module.exports = db;
user.js
const db = require("./conn");
let user = await db.collection("user").find({}).toArray();
I meet an issue that sometimes I will get an error Topology is closed, how can I close the db connection in this case? Thank you.

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}`)
})
});

Getting an Error: querySrv ECONNREFUSED _mongodb._tcp.cluster0-9esxx.gcp.mongodb.net

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;

MongoDB Atlas connection keeps dropping

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

Mongoose & MongoDB connection on production

What are best practicies to handle mongodb connection using mongoose on production?
This is my code
connectToDatabase.js
'use strict';
const mongoose = require('mongoose');
const mongodb = require('mongodb');
mongoose.Promise = require('bluebird');
const { Db, Server } = mongodb;
const database = 'test';
const connectToDatabase = (callback) => {
if (process.env.NODE_ENV == 'test') return false;
const db = new Db(database new Server('localhost', 27017));
db.open()
.then(() => {
mongoose.connect(`mongodb://localhost/${database}`, { config: { autoIndex: false } });
mongoose.connection
.once('open', () => {
console.log(`Connected to database ${database}`);
callback(db);
})
.on('error', (error) => {
console.warn('Warning', error);
});
});
};
module.exports = connectToDatabase;
app.js
const connectToDatabase = require('./connectToDatabase');
connectToDatabase(() => {
// run server
});
I don't know exactly what happening when connection to database is interrupted, Is mongoose trying connect to database again?

Resources