1//with mongoose
2
3const mongoose = require('mongoose');
4
5mongoose.connect(
6 mongoURI,
7 {
8 useNewUrlParser: true,
9 useUnifiedTopology: true
10 },
11 (err) => {
12 if (err) console.log(err);
13 app.listen(3000);
14 }
15);
16/********************************************************************/
17// with mongodb lib
18const mongodb = require('mongodb');
19
20const MongoClient = mongodb.MongoClient;
21
22let _db;
23// you can replace test with any database name that you want
24const mongoConnect = (cb) => {
25 MongoClient.connect('mongodb://127.0.0.1:27017/test')
26 .then((client) => {
27 _db = client.db();
28 cb()
29 console.log('Connected to MongoDb');
30 }).catch((err) => {
31 console.log(err);
32 });
33}
34//after your server started you can use getDb to access mongo Database
35const getDb = () => {
36 if (_db) return _db;
37 throw 'No database found';
38}
39
40exports.mongoConnect = mongoConnect;
41exports.getDb = getDb;
1
2//connect with mongodb
3mongoose.connect('mongodb://localhost:27017/your_db_name', {useNewUrlParser: true});
4//you can also specify with user and pass
5mongoose.connect('mongodb://username:password@host:port/database?options...', {useNewUrlParser: true});
6//or goto docs https://mongoosejs.com/docs/connections.html
1// create folder config and create two files below mentioned...
2
3// default.json
4{
5 "mongoURI": "add_your_key =_here"
6}
7
8/// db.js
9const mongoose = require("mongoose");
10const config = require("config");
11const db = config.get("mongoURI");
12
13const connectDB = async () => {
14 try {
15 await mongoose.connect(db, {
16 useNewUrlParser: true,
17 useCreateIndex: true,
18 useFindAndModify: false,
19 });
20 console.log("MongoDB connected...");
21 } catch (err) {
22 console.log(err.message);
23 process.exit(1);
24 }
25};
26
27# DONE ✅
28
29// dependencies
30 npm i express bcryptjs jsonwebtoken config express-validator mongoose
31
32// dev-dependencies
33 npm i -D nodemon concurrently
1async function main(){
2 /**
3 * Connection URI. Update <username>, <password>, and <your-cluster-url> to reflect your cluster.
4 * See https://docs.mongodb.com/ecosystem/drivers/node/ for more details
5 */
6 const uri = "mongodb+srv://<username>:<password>@<your-cluster-url>/test?retryWrites=true&w=majority";
7
8
9 const client = new MongoClient(uri);
10
11 try {
12 // Connect to the MongoDB cluster
13 await client.connect();
14
15 // Make the appropriate DB calls
16 await listDatabases(client);
17
18 } catch (e) {
19 console.error(e);
20 } finally {
21 await client.close();
22 }
23}
24
25main().catch(console.error);
26