使用express将MongoDB查询结果作为JSON发送

Ama*_*ros 11 javascript mongodb node.js express mongojs

我正在编写一个应用程序,我使用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);
        }
    });
}
Run Code Online (Sandbox Code Playgroud)

server.js

app.post("/get_users_list", function(req, res) {
    var body = req.body;
    db.getUsersByCity(body.city, res);
});
Run Code Online (Sandbox Code Playgroud)

这是有效的,因为正如你所看到的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)
Run Code Online (Sandbox Code Playgroud)

如何正确发送JSON响应而不将响应对象发送到我的数据库模块?

PSdb.js当我做出更改时,第36行的内容是callback(data);.

Gee*_*Jan 5

你是对的,db.js不应该打电话res甚至不知道.保持分离是件好事.

在此之后(未经测试):

db.js

    var getUsersByCity = function(city, cb) {
        db.users.find({'city': city}).toArray(cb);
    }
Run Code Online (Sandbox Code Playgroud)

server.js

    app.post("/get_users_list", function(req, res) {
        var body = req.body;
        db.getUsersByCity(body.city, function(err, data){
            if (err) {
                console.log(err);
                return res(err);
            } else {
                console.log(data);
                return res.json(data);
            }
        });
    });
Run Code Online (Sandbox Code Playgroud)