[英]Mongoerror: failed to connect to server localhost:27017 on first connect
[英]MongoError: failed to connect to server [localhost:27017] on first connect (ECONNREFUSED)
我剛剛將MongoDB添加到使用npm init
命令創建的Node.js項目的依賴項中。 我的index.js代碼是:
var MongoClient = require('mongodb').MongoClient
, assert = require('assert');
// Connection URL
var url = 'mongodb://localhost:27017/mydatabase';
// Use connect method to connect to the server
MongoClient.connect(url, function(err, db) {
assert.equal(null, err);
console.log("Connected successfully to server");
db.close();
});
但是,當我執行代碼時,它將引發以下錯誤:
AssertionError: null == { MongoError: failed to connect to server [localhost:27017] on first connect [MongoError: connect ECONNREFUSED 127.0.0.1:27017]
我真的不知道該如何解決。 我遵循了一些報告相同錯誤的指南,但無法修復。
我應該在調制解調器上插入端口嗎? 我應該用我的IP替換“ localhost”嗎? 我還應該做其他事情嗎?
請幫我!
更新:
我在Android設備上安裝了MongoDB服務器,並用mongodb://ANDROID-DEVICE-LOCAL-IP:27017/mydatabase
替換了url
變量,它現在可以工作了。
我如何完成將數據庫放置在計算機上的工作? 防火牆是否阻止傳入連接? 這就是為什么它可以在Android上但不能在Windows上運行的原因?
我已解決問題!
我在cmd中運行mongod -dbpath "MY-PATH"
,現在可以使用了。
發生錯誤是因為27017端口上沒有監聽任何內容。 現在mongod
程序正在偵聽該端口上的連接,因此不再拒絕來自我的項目的連接。
制作一個像config.js
這樣的配置文件
module.exports = {
'secretKey': '12345-67890-09876-54321',
'mongoUrl' : 'mongodb://localhost:27017/cubs'
}
並在服務器代碼中要求該文件
var config = require('./config');
var mongoose = require('mongoose');
mongoose.connect(config.mongoUrl);
var db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function () {
console.log("Connected correctly to server");
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.