Help us understand the problem. What is going on with this article?

node.js から mongodb接続時にconnect ECONNREFUSED

More than 5 years have passed since last update.

事象

node.jsからmongodbに接続しようとプログラムを作成して実行したところ
以下エラーがでてまう。

[vagrant@localhost nodejs]$ node mongo.js 
{ name: 'MongoError', message: 'connect ECONNREFUSED' }

プログラムは以下

var MongoClient = require('mongodb').MongoClient,
    settings = require('./settings');
MongoClient.connect("mongodb://"+settings.host+"/"+settings.db, function(err, db) {
    if (err) { return console.dir(err); }
    console.log("connected to db");
    db.collection("users", function(err, collection) {
        var docs = [
            {name: "taguchi", score: 40},
            {name: "fkoji", score: 80},
            {name: "dotinstall", score: 60}
        ];
        collection.insert(docs, function(err, result) {
            console.dir(result);
        });
    });
});

解決方法

  • まず、そもそも/data/dbをつくっていなかったので、つくりました。
$ sudo mkdir -p /data/db
  • mongodbに接続して、プログラム実行前に、nodedbデータベースおよびusersコレクションを作りました。
$ mongo nodedb
 > db.createCollection('users')
  • プログラム中の以下の記述を
MongoClient.connect("mongodb://"+settings.host+"/"+settings.db,
MongoClient.connect("mongodb://localhost:1337/"+settings.db,

に変更しました。

これで接続できるようになりました。

good ruck!

akippiko
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
No comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
ユーザーは見つかりませんでした