Node Js with NoSQL Database - aakash14goplani/FullStack GitHub Wiki

Topics Covered


Configuration

  1. Browse cloud.mongodb.com -> Build New Cluster -> Keep defaults (you can change cluster name if required) -> click Create Cluster

  2. 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
  3. Add MongoDB driver: npm install --save mongodb

  4. Within Cluster -> Connect -> Connect Your application -> Driver Version: Node.js 3.0 or later -> Copy URL


Connect to MongoDB

  • 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, use MongoClient to connect with database
    const mongoConnect = require('./util/nosql_database');
    ...
    mongoConnect(client => {
       console.log('client status: ', client);
       app.listen(4200, 'localhost');
    });