私はmongodbとHapi.jsを初めて使用しています。私は、読み取り要求のAPIを作成しようとしていますが、server.routeにハンドラメソッドを記述する方法がわかりません。私は、ホームページのパスに行くmongodh + hapi.js:コレクションが定義されていませんか?
'use strict';
var MongoClient = require('mongodb').MongoClient; //using version 3.x
var Hapi = require('hapi');//using v16
var url = 'mongodb://****:****@ds131687.mlab.com:31687/learning_mongo';
var db;
var server = new Hapi.Server();
server.connection({
port:8080
});
server.route([
// Get tour list
{
method: 'GET',
path: '/api/tours',
handler: function(request, reply){
collection.find().toArray(function(err,tours){
reply(tours);
});
}
},
// Home page
{
method: 'GET',
path: '/',
handler: function(request, reply) {
reply("Hello world from Hapi/Mongo example.");
}
}
]);
var tours = function(db, callback) {
var collection = db.collection('tours');
collection.find().toArray(function(err, docs){
console.log(docs);
callback;
});
};
MongoClient.connect(url, function(err,client) {
server.start(function(err) {
tours(client.db('learning_mongo'), function(){
console.log('Hapi is listening to http://localhost:8080');
client.close();
});
});//end server
})
が正常に動作しますが、私はパスを./api/toursに行くとき:
は、ここで私は私のmongoclientはHAPIに設定されている方法です端末で次のエラーが発生する:
Debug: internal, implementation, error
ReferenceError: Uncaught error: collection is not defined
at handler (/home/ubuntu/workspace/index.js:22:13)
at Object.internals.handler (/home/ubuntu/workspace/node_modules/hapi/lib/handler.js:101:51)
at request._protect.run (/home/ubuntu/workspace/node_modules/hapi/lib/handler.js:32:23)
at module.exports.internals.Protect.internals.Protect.run (/home/ubuntu/workspace/node_modules/hapi/lib/protect.js:60:12)
at exports.execute (/home/ubuntu/workspace/node_modules/hapi/lib/handler.js:26:22)
at each (/home/ubuntu/workspace/node_modules/hapi/lib/request.js:401:16)
at iterate (/home/ubuntu/workspace/node_modules/items/lib/index.js:36:13)
at done (/home/ubuntu/workspace/node_modules/items/lib/index.js:28:25)
at module.exports.internals.Auth.internals.Auth._authenticate (/home/ubuntu/workspace/node_modules/hapi/lib/auth.js:222:16)
at internals.Auth.authenticate (/home/ubuntu/workspace/node_modules/hapi/lib/auth.js:197:17)
コレクションを正しく定義するにはどうすればよいですか?ありがとうございました。
ありがとうございます!あなたの例を適用すると、エラーが発生しました:TypeError:nullのプロパティ 'db'を読み込めません。 db = client.db( 'learning_mongo') – redshift
修正済み:認証に問題があったため、URLが正しいことを確認する必要がありました。そうではありませんでしたので、私はそれを修正しました。ありがとう! – redshift