Express、Node.js、および MongoDB (mongojs を使用) を使用するアプリケーションを作成しています。モジュールdb.js
と がありserver.js
、以下のスニペットがあります。
db.js
var getUsersByCity = function(city, callback) {
db.users.find({'city': city}).toArray(function(err, data) {
if (err) {
callback(err);
console.log(err);
} else {
console.log(data);
callback.json(data);
}
});
}
サーバー.js
app.post("/get_users_list", function(req, res) {
var body = req.body;
db.getUsersByCity(body.city, res);
});
callback.json(data)
ご覧のとおり、 を使用する必要があるときに を(おそらく間違って) 使用しているため、機能していますcallback(data)
。db.js
モジュールは応答を送信する責任を負うべきではなく、コールバックとして関数に渡す必要があると思いres.json
ます。
問題は、私が正しいと思う方法で物事を行うと、次のエラーに直面することです:
path_to_my_app/node_modules/mongojs/node_modules/mongodb/lib/mongodb/connection/base.js:245
throw message;
^
TypeError: Cannot call method 'get' of undefined
at res.json (path_to_my_app/node_modules/express/lib/response.js:189:22)
at path_to_my_app/db.js:36:13
at path_to_my_app/node_modules/mongojs/node_modules/mongodb/lib/mongodb/cursor.js:163:16
at commandHandler (path_to_my_app/node_modules/mongojs/node_modules/mongodb/lib/mongodb/cursor.js:706:16)
at path_to_my_app/node_modules/mongojs/node_modules/mongodb/lib/mongodb/db.js:1843:9
at Server.Base._callHandler (path_to_my_app/node_modules/mongojs/node_modules/mongodb/lib/mongodb/connection/base.js:445:41)
at path_to_my_app/node_modules/mongojs/node_modules/mongodb/lib/mongodb/connection/server.js:468:18
at MongoReply.parseBody (path_to_my_app/node_modules/mongojs/node_modules/mongodb/lib/mongodb/responses/mongo_reply.js:68:5)
at null.<anonymous> (path_to_my_app/node_modules/mongojs/node_modules/mongodb/lib/mongodb/connection/server.js:426:20)
at EventEmitter.emit (events.js:95:17)
応答オブジェクトを DB モジュールに送信せずに JSON 応答を適切に送信するにはどうすればよいですか?
PSの 36 行目の内容はdb.js
、変更を加えると ですcallback(data);
。