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;