I have to connect node js app running on local machine(laptop) to mongodb running on deigtal ocean vps. I changed bindip in mongodb conf file. from local machine(laptop) the mongodb connection uri is below: mongodb://username:password@digital_ocean_server_ip:27017/animal
db.js
const mongoose = require("mongoose");
const connectDB = async (type = 0) => {
try {
//process.env.MONGO_URI is .env var which contains the DB URL
const conn = await mongoose.connect(process.env.MONGO_URI, {
useNewUrlParser: true,
useUnifiedTopology: true,
});
console.log(`MongoDb Connected: ${conn.connection.host}`);
} catch (err) {
console.log(err);
console.log("database connection error");
}
};
module.exports = connectDB;
.env
MONGO_URI=mongodb://username:password@digital_ocean_server_ip:27017/animal
app.js
//import db.js file in your app.js/index.js/server.js
const connectdb = require("./db");
connectdb();