我正在编写一个使用 express、Node.js 和 MongoDB(使用 mongojs)的应用程序。我有一个模块db.js
和一个server.js
,它们有下面的片段。
数据库.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)
如何正确发送 JSON 响应而不将响应对象发送到我的数据库模块?
PSdb.js
当我进行更改时,第 36 行的内容是callback(data);
.