【问题标题】:Trying to connect node.js to a mongodb, getting successful response but no connection尝试将 node.js 连接到 mongodb,获得成功响应但没有连接
【发布时间】:2019-03-26 13:27:23
【问题描述】:

我一直按照在线说明在 node.js 上使用 mongoose 设置 mongodb 数据库。我已经设法让 mongodb 运行并在端口 27017 上侦听,但是当我在 node.js 中运行我的连接代码时,即使 mongo.db 没有运行并且我没有看到任何更新,我也会得到成功的响应mongo.db 表示它已收到任何数据。

我已经尝试了很多来自互联网的不同示例,但无法让它们中的任何一个起作用。

所以我有我的MongoDB 说:

2019-03-26T12:00:46.039+0000 I NETWORK  [initandlisten] waiting for connections on port 27017

这是我尝试使用的基本代码,因为我的原始 API 无法正常工作:

//sample.js

var mongoose = require('mongoose');

mongoose.connect('mongodb://localhost/test', function(err){

  if(!err) console.log('Successfully Connected');

  console.log(mongoose.connection.host);

  console.log(mongoose.connection.port);
});

我在运行时收到此响应

node sample.js

Successfully Connected

localhost

27017

但即使我的 mongo.db 已关闭,我也会收到此响应,所以我认为有一些错误,我不确定如何检查它们是否正确连接。

【问题讨论】:

    标签: javascript node.js mongodb mongoose


    【解决方案1】:

    这对我有用。尝试设置一些调试以找出发生了什么。

    mongoose.set('debug', true);
    
    mongoose.connect("mongodb://localhost:27017/test", {useNewUrlParser: true})
        .then(() => {
            console.log('connected to the db');
         })
        .catch(err => {
            console.log('connection failed ' + err);
        }); 
    

    【讨论】:

    • 您好,我尝试这样做,但出现了一些错误 - 意外令牌位于:'.catch'
    • 抱歉,我在复制时遗漏了几个括号。请再试一次
    • 谢谢,它可以工作,但当我还没有启动我的 mongodb 时,它仍然显示“已连接到数据库”。它可能在我不知道的情况下运行吗?
    • 可能是这样。您使用哪个操作系统?尝试mongo 通过命令行连接到它。如果正在运行,它将显示服务的状态
    • 谢谢!我认为我对它的工作原理有错误的理解。
    【解决方案2】:

    我认为您必须检查 API 才能连接。

    https://mongoosejs.com/docs/connections.html

    第二个参数是选项,第三个是回调 - 但你似乎已经将回调作为第二个参数传递 - 另外,检查你得到什么作为响应

    mongoose.connect(uri, options, function(error) {
      // Check error in initial connection. There is no 2nd param to the callback.
    });
    
    // Or using promises
    mongoose.connect(uri, options).then(
      () => { /** ready to use. The `mongoose.connect()` promise resolves to undefined. */ },
      err => { /** handle initial connection error */ }
    );

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-03-18
      • 2014-11-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-12-01
      • 2018-08-27
      相关资源
      最近更新 更多