【问题标题】:Cant connect to Mongo Database [duplicate]无法连接到 Mongo 数据库 [重复]
【发布时间】:2018-10-22 10:06:32
【问题描述】:

对不起,如果这个问题是菜鸟问题(我是新手)...

我一直在尝试设置我的应用程序以连接到数据库,但我收到此错误,我似乎无法找到问题。

这是代码

    const express = require('express');
    const app = express();
    const ejs = require('ejs');
    const path = require('path');
    const mongo = require('mongodb').MongoClient;
    const dbUrl = 'mongodb://localhost:3000/contractformapp';
    const bodyParser = require('body-parser');
    const ObjectId = require('mongodb').ObjectId;

    mongo.connect(dbUrl, function(err, contract) {
        if (err) {
            console.log("Error connecting to the database");
        } else {
            console.log("Connection to database was successful");
            contracts = contract.db('contractformapp').collection('contracts');
        }
    });

    app.use(bodyParser.json());
    app.use(bodyParser.urlencoded({ extended: false }));



    app.get('/', function (req, res) {
        contracts.find({}).toArray(function (err, docs) {
            if (err) {
                console.log(err);
                return;
            }
            res.render('index', { docs: docs });
        });
    });


app.listen(3000, 'localhost', (err) => {
    if (err) {
        console.log('err');
    } else {
        console.log('Server started listening');
    }
});


app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');

当我尝试运行 nodemon 并打开 http://localhost:3000/

Server started listening
Error connecting to the database
ReferenceError: contracts is not defined

【问题讨论】:

标签: javascript mongodb


【解决方案1】:

您的 mongo 服务器不应与您的 express 服务器位于同一端口。我认为 mongdb 的默认值是 27017,所以可能就是它所在的位置。

const dbUrl = 'mongodb://localhost:27017/contractformapp';

那个,并确保你的 mongodb 已经启动并运行。

【讨论】:

  • 是的,我完全失败了,非常感谢。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-07-30
  • 2020-11-24
  • 1970-01-01
  • 2011-07-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多