質問をすることでしか得られない、回答やアドバイスがある。

15分調べてもわからないことは、質問しよう!

新規登録して質問してみよう
ただいま回答率
85.48%
MongoDB

MongoDBはオープンソースのドキュメント指向データベースの1つです。高性能で、多くのリトルエンディアンシステムを利用することができます。

Node.js

Node.jsとはGoogleのV8 JavaScriptエンジンを使用しているサーバーサイドのイベント駆動型プログラムです。

Q&A

1回答

2471閲覧

Node.jsとmongoDBがうまく接続できない

aiai8976

総合スコア112

MongoDB

MongoDBはオープンソースのドキュメント指向データベースの1つです。高性能で、多くのリトルエンディアンシステムを利用することができます。

Node.js

Node.jsとはGoogleのV8 JavaScriptエンジンを使用しているサーバーサイドのイベント駆動型プログラムです。

0グッド

0クリップ

投稿2019/08/12 03:46

前提・実現したいこと

クライアントからサーバ、サーバからMongoDBにアクセスして、保存しているJsonファイルをクライアントに返したいのですが、下に掲載しているapp.jsとして、MongoDBにアクセスし、オブジェクトを取得することはできました。
しかし、Node.jsの処理の一部とした(クライアントからサーバに処理要求した)ときにMongoDBにconnectすることができません。
何が原因なのか見当がつきません。
わかる方がいましたら、コメントお願いします。

発生している問題・エラーメッセージ

コネクトに入っていないことが分かると思います。

hasegawa@hasegawa-W76OC:~/デスクトップ/akiyama/Node.js$ sudo node webServer.js Server running at http://localhost:80/ / /js/three.js-master/build/three.min.js /js/OrbitControls.js /get_value レスポンス _http_outgoing.js:595 throw new ERR_INVALID_ARG_TYPE('first argument', ^ TypeError [ERR_INVALID_ARG_TYPE]: The first argument must be one of type string or Buffer. Received type undefined at write_ (_http_outgoing.js:595:11) at ServerResponse.write (_http_outgoing.js:567:10) at Object.getValue (/home/hasegawa/デスクトップ/akiyama/Node.js/webServer.js:104:17) at Server.<anonymous> (/home/hasegawa/デスクトップ/akiyama/Node.js/webServer.js:128:29) at Server.emit (events.js:198:13) at parserOnIncoming (_http_server.js:677:12) at HTTPParser.parserOnHeadersComplete (_http_common.js:109:17)

該当のソースコード

app.js

const MongoClient = require('mongodb').MongoClient; const assert = require('assert'); // Connection URL const url = 'mongodb://localhost:27017'; // Database Name const dbName = 'study'; //結果 var value; const client = new MongoClient(url,{useNewUrlParser: true}); // Use connect method to connect to the server client.connect(function(err) { assert.equal(null, err); console.log("Connected correctly to server"); const db = client.db(dbName); findDocuments(db, function() { client.close(); }); }); const findDocuments = function(db, callback) { // Get the documents collection const collection = db.collection('user'); // Find some documents collection.find({}).toArray(function(err, docs) { assert.equal(err, null); console.log("Found the following records"); //for (var document of docs) { //console.log("Found the following records"); //console.log(document[dist]); //console.log(document[rot]); //result=push(document.dist); //result=push(document.rot); //} console.log(docs); callback(docs); }); }

webServer.js

// 必要なファイルを読み込み var http = require('http'); var url = require('url'); var fs = require('fs'); var server = http.createServer(); // http.createServerがrequestされたら、(イベントハンドラ) server.on('request', function (req, res) { // Responseオブジェクトを作成し、その中に必要な処理を書いていき、条件によって対応させる var Response = { "renderHTML": function () { var template = fs.readFile('./template/index.html', 'utf-8', function (err, data) { // HTTPレスポンスヘッダを出力する res.writeHead(200, { 'content-Type': 'text/html' }); // HTTPレスポンスボディを出力する res.write(data); res.end(); }); }, "getThree": function () { var template = fs.readFile('./js/three.js-master/build/three.min.js', 'utf-8', function (err, data) { // HTTPレスポンスヘッダを出力する res.writeHead(200, { 'content-Type': 'text/javascript' }); // HTTPレスポンスボディを出力する res.write(data); res.end(); }); }, "getOrbit": function () { var template = fs.readFile('./js/OrbitControls.js', 'utf-8', function (err, data) { // HTTPレスポンスヘッダを出力する res.writeHead(200, { 'content-Type': 'text/javascript' }); // HTTPレスポンスボディを出力する res.write(data); res.end(); }); }, "getValue": function () { const MongoClient = require('mongodb').MongoClient; const assert = require('assert'); // Connection URL const url = 'mongodb://localhost:27017'; // Database Name const dbName = 'study'; //結果 var value; const client = new MongoClient(url,{useNewUrlParser: true}); // Use connect method to connect to the server client.connect(function(err) { assert.equal(null, err); console.log("Connected correctly to server"); const db = client.db(dbName); findDocuments(db, function() { client.close(); }); }); const findDocuments = function(db, callback) { console.log("OK"); // Get the documents collection const collection = db.collection('user'); // Find some documents collection.find({}).toArray(function(err, docs) { assert.equal(err, null); console.log("Found the following records"); //for (var document of docs) { //console.log("Found the following records"); //console.log(document[dist]); //console.log(document[rot]); //result=push(document.dist); //result=push(document.rot); //} console.log(docs); callback(docs); }); } // HTTPレスポンスヘッダを出力する res.writeHead(200, { 'content-Type': 'text/html' }); console.log("レスポンス"); //console.log(result); // HTTPレスポンスボディを出力する res.write(value); res.end(); } }; // urlのpathをuriに代入 var uri = url.parse(req.url).pathname; console.log(uri); // URIで行う処理を分岐させる if (uri === "/") { // URLが「http://localhost:8080/」の場合、"renderHTML"の処理を行う Response["renderHTML"](); return; } else if (uri === "/js/three.js-master/build/three.min.js") { // URLが「http://localhost:8080/js/three.js-master/build/three.min.js」の場合、"getThree"の処理を行う Response["getThree"](); return; } else if (uri === "/js/OrbitControls.js") { // URLが「http://localhost:8080/js/OrbitControls.js」の場合、"getOrbit"の処理を行う Response["getOrbit"](); return; } else if (uri === "/get_value") { // URLが「http://localhost:8080/get_value」の場合、"getThree"の処理を行う Response["getValue"](); return; }; }); // 指定されたポート(8080)でコネクションの受け入れを開始する server.listen(80); console.log('Server running at http://localhost:80/');

###試したこと
curl http://~/get_valueでクライアントからとサーバからアクセスしましたが、

Empty reply from server

となりました。

また、クライアントとサーバのファイアウォールが無効化されていることも確認しました。
さらに、mongoDBのポート番号は27017なのですが、

netstat -an| grep 27017 ~ LISTEN

となっていました。

補足情報(FW/ツールのバージョンなど)

OS:ubuntu
mongodb:4.0.10

気になる質問をクリップする

クリップした質問は、後からいつでもMYページで確認できます。

またクリップした質問に回答があった際、通知やメールを受け取ることができます。

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

guest

回答1

0

エラーメッセージを見たらいいと思いますが

TypeError [ERR_INVALID_ARG_TYPE]: The first argument must be one of type string or Buffer. Received type undefined at write_ (_http_outgoing.js:595:11) at ServerResponse.write (_http_outgoing.js:567:10) at Object.getValue (/home/hasegawa/デスクトップ/akiyama/Node.js/webServer.js:104:17)

となっていて、webServer.js:104というのは

res.write(value);

ですよね。

そこで The first argument must be one of type string or Buffer. Received type undefined となっているわけですから、valueがおかしいですね。undefinedになってしまっていると。

投稿2019/08/12 08:51

kabao

総合スコア648

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

aiai8976

2019/08/12 15:33

コメントありがとうございます。 はい。その原因は、mongoDBにアクセスできていないため、「定義されていない」状態になっているものだと思われます。 ポート番号やファイアウォール以外で考えられる原因はありますでしょうか。
kabao

2019/08/12 16:48

webServer.jsの60行目でvar value;として宣言したあと、64行目〜72行目付近のMongoDBに対するconnect処理で接続できていようがいまいが、valueに対して何も操作してなくないですか?undefinedのままになっているだけでは?
aiai8976

2019/08/15 02:22

すいません。そこは凡ミスでした。 でもやはりそもそもコネクトできていないため関数の中に入れていないです。
guest

あなたの回答

tips

太字

斜体

打ち消し線

見出し

引用テキストの挿入

コードの挿入

リンクの挿入

リストの挿入

番号リストの挿入

表の挿入

水平線の挿入

プレビュー

まだベストアンサーが選ばれていません

会員登録して回答してみよう

アカウントをお持ちの方は

15分調べてもわからないことは
teratailで質問しよう!

ただいまの回答率
85.48%

質問をまとめることで
思考を整理して素早く解決

テンプレート機能で
簡単に質問をまとめる

質問する

関連した質問