【问题标题】:cant connect to Local mongodb server with nodejs无法使用 nodejs 连接到本地 mongodb 服务器
【发布时间】:2016-02-26 01:46:24
【问题描述】:

当尝试从项目目录连接到 mongo db 时,我得到了这个

/Users/tadeothompson/Documents/design work/stressful/site/node_modules/connect-mongo/lib/connect-mongo.js:133 抛出错误; ^ MongoError:无法连接到服务器 在 Collection.listIndexes (/Users/tadeothompson/Documents/design work/stressful/site/node_modules/mongoose/node_modules/mongodb/lib/collection.js:1712:11) 在 indexInformation (/Users/tadeothompson/Documents/design work/stressful/site/node_modules/mongoose/node_modules/mongodb/lib/db.js:1531:25) 在 Db.indexInformation (/Users/tadeothompson/Documents/design work/stressful/site/node_modules/mongoose/node_modules/mongodb/lib/db.js:1498:44) 在 ensureIndex (/Users/tadeothompson/Documents/design work/stressful/site/node_modules/mongoose/node_modules/mongodb/lib/db.js:1003:8) 在 Db.ensureIndex (/Users/tadeothompson/Documents/design work/stressful/site/node_modules/mongoose/node_modules/mongodb/lib/db.js:982:44) 在 ensureIndex (/Users/tadeothompson/Documents/design work/stressful/site/node_modules/mongoose/node_modules/mongodb/lib/collection.js:1772:13) 在 Collection.ensureIndex (/Users/tadeothompson/Documents/design work/stressful/site/node_modules/mongoose/node_modules/mongodb/lib/collection.js:1760:44) 在 connectionReady (/Users/tadeothompson/Documents/design work/stressful/site/node_modules/connect-mongo/lib/connect-mongo.js:141:27) 在 Db.collection (/Users/tadeothompson/Documents/design work/stressful/site/node_modules/mongoose/node_modules/mongodb/lib/db.js:425:20) 在 initWithNativeDb (/Users/tadeothompson/Documents/design work/stressful/site/node_modules/connect-mongo/lib/connect-mongo.js:207:20) 在 process._tickCallback (node.js:355:11) 在 Function.Module.runMain (module.js:503:11) 启动时 (node.js:129:16) 在 node.js:814:3

设法使用简单的应用程序进行连接(代码如下)

*

var MongoClient = require('mongodb').MongoClient;
    // Connect to the db
    MongoClient.connect("mongodb://localhost:27017/exampleDb", function(err, db) {
      if(!err) {
        console.log("We are connected");
      }
    });

*

the main node file of the app in question code is below:


var express = require('express');
var bodyParser = require('body-parser');
var cookieParser = require('cookie-parser');
var expressSession = require('express-session');
var mongoStore = require('connect-mongo')({session: expressSession});
var mongoose = require('mongoose');
require('./models/users_model.js');
var conn = mongoose.connect('mongodb://localhost:27017/stressfullproject');
var app = express();
app.engine('html', require('ejs')._express); 
app.set('views', './site' + '/views');        
app.set('view engine', 'html');
app.use(bodyParser());
app.use(cookieParser());
app.use(expressSession({
    secret: 'stress',
    cookie: {maxAge: 60*60*1000},
    store: new mongoStore({
        db: mongoose.connection.db,
        collection: 'sessions'
    })
}));
require('./routes/routes')(app);
app.listen(80);

*

我定义的架构

 *var mongoose = require('mongoose'),
    Schema = mongoose.Schema;
var UserSchema = new Schema({
    username: { type: String, unique: true },
    email: String,
    hashed_password: String
})
mongoose.model('User', UserSchema)*

因为我可以连接到其他应用程序,我认为这是我的一个模块的问题?我搜遍了。

提前致谢

【问题讨论】:

  • 能否提供完整的堆栈跟踪信息。

标签: node.js mongodb mongoose


【解决方案1】:

MongoDB版本v4.2.6 --- Node.js 版本:v14.2.0

首先,确保您正在运行 mongodb 本地服务器,通过以下命令检查现有数据库:

show dbs

输出:

现在我想连接数据库tours-test

先通过命令安装mongooes

npm i mongoose

现在在你的 connection.js 中

const mongoose = require('mongoose');

const conStr = 'mongodb://localhost:27017/tours-test';
mongoose
  .connect(conStr, {
    usedNewUrlParser: true,
    useCreateIndex: true,
    useFindAndModify: false,
  })
  .then((con) => console.log('DB connection successful'));
// remember mongoose.connect() return Promise

【讨论】:

    【解决方案2】:

    我在另一个堆栈溢出帖子here中找到了答案

    问题是会话(或猫鼬之外的其他东西)在猫鼬建立连接之前试图连接到数据库。

    【讨论】:

      【解决方案3】:

      两个问题之一 - 您正在调用未定义的模式(猫鼬),或者您有一个需要 next 但 next 未定义的函数。我已经多次遇到这个问题,并且记录了猫鼬缺乏错误处理。您需要在 app.js 文件的早期定义一些错误处理。

      【讨论】:

      • 我已经在另一个模块中定义了架构:(上面添加的代码)。我必须在“下一个”问题上回复您
      【解决方案4】:

      我最好的猜测是您正在使用两个模块,即 MongoClient 和 mongoose 都试图连接到端口 27017。现在在这场比赛中,只有一个会获胜并锁定该端口。如果您尝试绑定到该端口,它将给您一个错误,类似于您在上面遇到的错误。我的建议,不要使用 MongoClient。只使用猫鼬。 mongoose 有很多帮助,youtube 上的许多视频教程都使用它。 如果那没有帮助,请告诉我。

      让我们为您准备一些代码吧。我现在不使用 MongoClient,但是当我以前写这段代码时,看看它的工作原理。如果没有,请粘贴堆栈跟踪。

      var MongoClient=require('mongodb').MongoClient,
      
      server=require('mongodb').Server;
      
      var mongoclient=new MongoClient(new server('localhost',27017));
      
      mongoclient.connect('mongodb://localhost:27017/course',function(err,db)
      {
          if(err) throw err;
          //var db=mongoclient.db('course');
          var query={'grade':100};
      
          db.collection('grades').findOne(query,function(err,doc)
              {
                  if(err) throw err;
                  console.dir(doc);
                  db.close();
              });
      });
      

      【讨论】:

      • 感谢您的帮助;我没有同时运行这两个模块。这个问题早在我创建“小型测试模块”之前就已经存在。我只创建了测试模块并单独运行它以查看是否会建立连接,希望能排除 mongod 服务器的问题。
      • 所以你的 mongod 服务器运行良好? mongod --dbpath ~/data/db打开连接??
      • 确保您的端口 27017 已释放。通过运行netstat -tulpn
      • 总比没有错误好,对吧?现在让我们调试它,看看会发生什么?您是否更改了集合和数据库的名称?确保在 mongo 控制台中运行相同的查询时得到一些结果。如果那里有你应该得到结果
      • mongod 服务器运行良好。它等待连接并在另一个终端中使用 'mongo' cmd 时打开一个。
      猜你喜欢
      • 2018-10-17
      • 2022-11-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-12-09
      • 2019-03-02
      • 2014-02-04
      相关资源
      最近更新 更多