无法连接到Mongo数据库

时间:2018-05-11 23:56:08

标签: javascript mongodb

如果这个问题是一个菜鸟(我在这里新)...

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

这是代码

    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

1 个答案:

答案 0 :(得分:0)

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

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

那,并确保你的mongodb正常运行。