-
Notifications
You must be signed in to change notification settings - Fork 1
Node Js with NoSQL Database
Aakash Goplani edited this page Mar 11, 2020
·
2 revisions
Topics Covered
-
Browse cloud.mongodb.com -> Build New Cluster -> Keep defaults (you can change cluster name if required) -> click Create Cluster
-
In Cluster -> Security tab ->
- Database Access -> Make sure to have at-least one user -> add User that has Read and Write Access to any database
- Network access -> IP White list -> Add your IP address to connect with cloud MongoDB
-
Add MongoDB driver:
npm install --save mongodb
-
Within Cluster -> Connect -> Connect Your application -> Driver Version:
Node.js 3.0 or later
-> Copy URL
- Following code connects to MongoDB. Use URL from Atlas (one retrieved in #4 of above section)
const mongodb = require('mongodb'); const MongoClient = mongodb.MongoClient; const mongoConnect = (callback) => { MongoClient .connect('mongodb+srv://test:[email protected]/test?retryWrites=true&w=majority',{ useUnifiedTopology: true, useNewUrlParser: true, }) .then(client => { console.log('connected to mongodb: ', client); callback(client); }) .catch(error => { console.log('error connecting to mongodb: ', error); callback(error); }); } module.exports = mongoConnect;
- Then in
app.js
, useMongoClient
to connect with databaseconst mongoConnect = require('./util/nosql_database'); ... mongoConnect(client => { console.log('client status: ', client); app.listen(4200, 'localhost'); });