node.js - 无法使用 mongoose 连接到 MongoDb。 MongoDB 安装在我的本地系统中

标签 node.js express mongoose

我无法使用 mongoose 连接到 MongoDb。我已经在本地系统中安装了 MongoDB

//Import the mongoose module
    var mongoose = require('mongoose');

    //Set up default mongoose connection`enter code here`
    var mongoDB = 'mongodb://localhost/my_database';
    mongoose.connect(mongoDB, {
      useMongoClient: true
    });

    //Get the default connection
    var db = mongoose.connection;

    //Bind connection to error event (to get notification of connection errors)
    db.on('error', console.error.bind(console, 'MongoDB connection error:'));

    module.exports = mongoose.connection;

收到错误:

// MongoDB connection error: { MongoError: failed to connect to server [localhost:27017] on first connect

最佳答案

我也遇到了同样的问题。似乎在连接字符串中使用 localhost 是问题所在。最好只使用 127.0.0.1 代替 localhost。在 Linux 中两者都工作良好,但在 Windows 中 localhost 有问题

示例:

const DB_URL="mongodb://127.0.0.1/<db_name>"

关于node.js - 无法使用 mongoose 连接到 MongoDb。 MongoDB 安装在我的本地系统中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46710909/

相关文章:

javascript - ENOENT:运行 fs.readFile 时没有此类文件或目录

node.js - app.all ('*' ) 和 app.use ('/' ) 之间的区别

node.js - 测试 NodeJS 应用程序时,我应该将 Capybara.app 设置为什么?

node.js - 使用 Mongoose 将数组元素设置为 null

JavaScript 执行引擎未指定?

javascript - 在没有 try/catch 的情况下检查 CosmosDB 项目是否存在

javascript - 客户端 &lt;script src ="/socket.io/socket.io.js">&lt;/script&gt; 未找到,使用 Express-generator 生成的项目

json - 使用 jQuery 发布 json 来表达

node.js - 非索引字段上的索引重复键

javascript - Mongoose 似乎不支持 $max 字段更新运算符,有什么建议吗?