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;
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