我正在编写一个应用程序,其中使用了 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);
}
});
}
server.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响应而不将响应对象发送到我的DB模块?
P.S. 当我进行更改时,db.js
的第36行内容为callback(data);
。