Phuc Nguyen
Phuc Nguyen

Reputation: 365

Can't connect to MongoDB with Nodejs

I am using Node js to try to connect to MongoDB. Here are the related code snippets:

{
  "port": 3001,
  "appPort": 8080,
  "host": "localhost:3001",
  "protocol": "http",
  "allowedOrigins": ["*"],
  "domain": "http://localhost:3001",
  "basePath": "",
  "mongo": "mongodb://100.10.10.10:27017/database",
  "mongoConfig": "",
  "mongoCA": "",
  "mongoSecret": "--- change me now ---"
}
MongoClient.connect(dbUrl, {useUnifiedTopology: true}, function(err, client) {
      if (err) {
        console.log(err);
        debug.db(`Connection Error: ${err}`);
        unlock(function() {
          throw new Error(`Could not connect to the given Database for server updates: ${dbUrl}.`);
        });
      }
      db = client.db(client.s.options.dbName);

      debug.db('Connection successful');
}

When I use 'npm start' to start the server, I got this error:

MongoServerSelectionError: connect EACCES 100.10.10.10:27017
    at Timeout._onTimeout (formio\node_modules\mongodb\lib\core\sdam\topology.js:438:30)
    at listOnTimeout (internal/timers.js:549:17)
    at processTimers (internal/timers.js:492:7) {
  reason: TopologyDescription {
    type: 'Unknown',
    setName: null,
    maxSetVersion: null,
    maxElectionId: null,
    servers: Map { '100.10.10.10:27017' => [ServerDescription] },
    stale: false,
    compatible: true,
    compatibilityError: null,
    logicalSessionTimeoutMinutes: null,
    heartbeatFrequencyMS: 10000,
    localThresholdMS: 15,
    commonWireVersion: null
  }
}

I have tried to enable/disable the firewall but the results still don't change. Could you help me fix it? Thanks More information about the repository: https://github.com/formio/formio

Upvotes: 1

Views: 979

Answers (1)

Jobin Selvanose
Jobin Selvanose

Reputation: 96

https://github.com/Jobin-S/shopping-cart/blob/master/config/connection.js

please look this repository you can see the example. Make an config file and require it in app.js

const mongoClient = require('mongodb').MongoClient

const state ={
    db:null
}

module.exports.connect = (done) => {
    const url = 'mongodb://localhost:27017';
    const dbName = 'shopping';

    mongoClient.connect(url,{ useUnifiedTopology: true }, (err, data) => {
        if(err) return done(err)
        state.db = data.db(dbName)
        done()
    })
}

module.exports.get = function(){
    return state.db
}

after making this config file. require config file and require in app.js file and write the code below

var db = require('./config/connection')
db.connect((err)=>{
  if(!err) console.log("Database connected successfully");
  else console.log(`Connection Error: ${err}`);
})

after that you can use database in any file.

const db = require('../config/connection')
addProduct: (product) => {
        return new Promise((resolve, reject) => {
            product.Price = parseInt(product.Price)
            db.get().collection(collection_name).insertOne(product).then((data) => {
            resolve(data.ops[0]._id)
            })
        })
    }

Upvotes: 2

Related Questions