【发布时间】:2023-03-13 00:45:01
【问题描述】:
我正在编写一个使用 express、Node.js 和 MongoDB(使用 mongojs)的应用程序。我有一个模块db.js 和一个server.js,下面有sn-ps。
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 响应?
P.S.我修改时db.js的第36行内容是callback(data);。
【问题讨论】:
标签: javascript node.js mongodb express mongojs