Last active
September 6, 2021 14:56
-
-
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...
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
db.connect((err)=>{ | |
if (err) { | |
console.log("Database connection Error :"+err); | |
}else{ | |
console.log("Database connected to port 27017"); | |
} | |
}) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var db = require('./config/connection') |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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