无法在localhost上为node.js启动MongoDB
我是node.js和MongoDB的初学者。我正在尝试设置这样的基本项目。
在我的项目目录中,我运行node init
,接受默认值,然后运行npm install --save mongodb
。在我的index.js中,我有以下代码:
// Import the mongodb module
var mongo = require('mongodb');
var MongoClient = require('mongodb').MongoClient;
var url = "mongodb://localhost:3333/mydb";
MongoClient.connect(url, function(err, db) {
if (err) throw err;
console.log("Database created!");
db.close();
});
现在,当我运行node index.js
时,我收到以下错误:
failed to connect to server [localhost:3333] on first connect [MongoNetworkError: connect ECONNREFUSED 127.0.0.1:3333]
我试过更改端口号但仍然得到相同的错误。我在这做错了什么?
回答如下:默认情况下,MongoDB服务器在端口27017上运行。您需要将连接字符串更改为mongodb://localhost:27017/mydb
。
无法在localhost上为node.js启动MongoDB
我是node.js和MongoDB的初学者。我正在尝试设置这样的基本项目。
在我的项目目录中,我运行node init
,接受默认值,然后运行npm install --save mongodb
。在我的index.js中,我有以下代码:
// Import the mongodb module
var mongo = require('mongodb');
var MongoClient = require('mongodb').MongoClient;
var url = "mongodb://localhost:3333/mydb";
MongoClient.connect(url, function(err, db) {
if (err) throw err;
console.log("Database created!");
db.close();
});
现在,当我运行node index.js
时,我收到以下错误:
failed to connect to server [localhost:3333] on first connect [MongoNetworkError: connect ECONNREFUSED 127.0.0.1:3333]
我试过更改端口号但仍然得到相同的错误。我在这做错了什么?
回答如下:默认情况下,MongoDB服务器在端口27017上运行。您需要将连接字符串更改为mongodb://localhost:27017/mydb
。