简体   繁体   English

无法从 Node JS 连接到 mongo 本地数据库

[英]cannot connect to mongo local DB from Node JS

I am learning Mongo DB, Mongoose and Node JS and I can't seem to connect my Node JS to local Mongo DB.我正在学习 Mongo DB、Mongoose 和 Node JS,但似乎无法将 Node JS 连接到本地 Mongo DB。

Here is my code:这是我的代码:

dbtest.js dbtest.js

    var express  = require('express');
    var app      = express();                               // create our app w/ express
    var mongoose = require('mongoose');                     // mongoose for mongodb
    var morgan = require('morgan');             // log requests to the console (express4)
    var bodyParser = require('body-parser');    // pull information from HTML POST (express4)
    var methodOverride = require('method-override'); // simulate DELETE and PUT (express4)

    var options = {
          useMongoClient: true,
          autoIndex: false, // Don't build indexes
          reconnectTries: Number.MAX_VALUE, // Never stop trying to reconnect
          reconnectInterval: 500, // Reconnect every 500ms
          poolSize: 10, // Maintain up to 10 socket connections
          // If not connected, return errors immediately rather than waiting for reconnect
          bufferMaxEntries: 0
};



    var Todo = mongoose.model('Todo', {
        text : String
    }, 'test');

    var status = {
    "status": "not connected"
    };

    app.get('/api/todos', function(req, res) {

            mongoose.connect('mongodb://127.0.0.1:27017/exampleDB',options,function(err)
    {
              if (err) {
              res.json(status);
            } else {
                res.json('Connected');
            }    
    });  
    });

    app.listen(8080);
    console.log("App listening on port 8080");

When I call api/todos GET request, the status JSON object is returned, meaning I cannot connect to the database.当我调用 api/todos GET 请求时,返回了状态 JSON 对象,这意味着我无法连接到数据库。

JSON 消息

I installed MongoDB Enterprise Server 3.14.10 completely and have it running but I don't know why my NodeJS application cannot connect.我完全安装了 MongoDB Enterprise Server 3.14.10 并运行了它,但我不知道为什么我的 NodeJS 应用程序无法连接。

Any suggestions are appreciated.任何建议表示赞赏。

您的第一个mongoose.connect()参数缺少用户名/密码组合:

mongoose.connect('mongodb://username:password@127.0.0.1:27017/exampleDB');

Try to connect db first before doing any action.尝试在执行任何操作之前先连接数据库。 Once it connected try to use inside your custom function.连接后尝试在您的自定义函数中使用。 Below code will helps you to test local database下面的代码将帮助您测试本地数据库

const express = require('express');
const app = express();
const port = 3000;
const mongoose = require('mongoose');

mongoose.connect('mongodb://localhost:27017/dbname', { useMongoClient: true });
mongoose.connection.on('connected', () => {
  console.log('Connected to database ');
}); 
mongoose.connection.on('error', (err) => {
  console.log('Database error: '+err);
});


// Start Server
app.listen(port, () => {
  console.log('Server started on port '+port);
});

Check your cmd window to see console.检查您的 cmd 窗口以查看控制台。

For connecting to a local mongodb, you can use this URI, replacing USER, PASSWORD are DB with your values :要连接到本地 mongodb,您可以使用此 URI,将 USER, PASSWORD are DB 替换为您的值:

mongodb://USER:PASSWORD@127.0.0.1/DB?authSource=admin

You don't need to provide the port 27017, because it's the default one for mongodb.您不需要提供端口 27017,因为它是 mongodb 的默认端口。

The trick here is to add with 'authSource=admin' for enabling the authentication.这里的技巧是添加 'authSource=admin' 以启用身份验证。

Documentation : https://docs.mongodb.com/manual/reference/connection-string/#examples文档: https : //docs.mongodb.com/manual/reference/connection-string/#examples

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM