Skip to content

Instantly share code, notes, and snippets.

@Muhammed-Rahif
Last active September 6, 2021 14:56
Show Gist options
  • Save Muhammed-Rahif/d755df1944ca4b46e92fe436e1575643 to your computer and use it in GitHub Desktop.
Save Muhammed-Rahif/d755df1944ca4b46e92fe436e1575643 to your computer and use it in GitHub Desktop.
This is a mongodb localhost:27017 connection code in node js express. We can connect simply mongodb(PORT: localhost:27017 ) to our node js project as this code...
db.connect((err)=>{
if (err) {
console.log("Database connection Error :"+err);
}else{
console.log("Database connected to port 27017");
}
})
var db = require('./config/connection')
const mongoClient = require('mongodb').MongoClient;
const state={
db:null
}
module.exports.connect=(done)=>{
const url='mongodb://localhost:27017';
const dbname='DB_NAME';
mongoClient.connect(url,{ useNewUrlParser: true, useUnifiedTopology: true },(err,data)=>{
if (err) {
return done(err)
}else{
state.db=data.db(dbname)
done()
}
})
}
module.exports.get=()=>{
return state.db
}
const mongoose = require("mongoose");
const server = "mongodb://localhost:27017";
const dbName = "DB_NAME_HERE";
const dbURI = server + "/" + dbName;
function connect() {
mongoose
.connect(dbURI, {
useNewUrlParser: true,
useUnifiedTopology: true,
useFindAndModify: false,
useCreateIndex: true,
})
.then(() => {
console.log("Database connection successful.");
})
.catch((err) => {
console.log("Database connection error : " + err);
});
}
module.exports = { connect };
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment