首页 > 解决方案 > 无法使用 Nodejs 连接到 MongoDB

问题描述

我正在使用 Node js 尝试连接到 MongoDB。以下是相关的代码片段:

{
  "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');
}

当我使用“npm start”启动服务器时,出现以下错误:

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

我尝试启用/禁用防火墙,但结果仍然没有改变。你能帮我修一下吗?谢谢 关于存储库的更多信息: https ://github.com/formio/formio

标签: node.jsmongodb

解决方案


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

请查看此存储库,您可以看到示例。制作一个配置文件并在 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
}

制作此配置文件后。需要配置文件并在 app.js 文件中需要并编写下面的代码

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

之后,您可以在任何文件中使用数据库。

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)
            })
        })
    }

推荐阅读