我无法使用 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/