繁体   English   中英

尝试将node.js连接到mongodb,获得成功响应但没有连接

[英]Trying to connect node.js to a mongodb, getting successful response but no connection

我一直遵循在线说明在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已关闭,我仍会收到此响应,因此我认为有一些错误,我不确定如何检查它们是否正确连接。

这对我有用。 尝试进行一些调试以找出正在发生的情况。

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

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

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

第二个参数是option,第三个参数是callback-但是您似乎已经将callback作为第二个参数传递了-另外,请检查您得到的响应是什么

 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 */ } ); 

暂无
暂无

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

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