te')); return $arr; } /* 遍历用户所有主题 * @param $uid 用户ID * @param int $page 页数 * @param int $pagesize 每页记录条数 * @param bool $desc 排序方式 TRUE降序 FALSE升序 * @param string $key 返回的数组用那一列的值作为 key * @param array $col 查询哪些列 */ function thread_tid_find_by_uid($uid, $page = 1, $pagesize = 1000, $desc = TRUE, $key = 'tid', $col = array()) { if (empty($uid)) return array(); $orderby = TRUE == $desc ? -1 : 1; $arr = thread_tid__find($cond = array('uid' => $uid), array('tid' => $orderby), $page, $pagesize, $key, $col); return $arr; } // 遍历栏目下tid 支持数组 $fid = array(1,2,3) function thread_tid_find_by_fid($fid, $page = 1, $pagesize = 1000, $desc = TRUE) { if (empty($fid)) return array(); $orderby = TRUE == $desc ? -1 : 1; $arr = thread_tid__find($cond = array('fid' => $fid), array('tid' => $orderby), $page, $pagesize, 'tid', array('tid', 'verify_date')); return $arr; } function thread_tid_delete($tid) { if (empty($tid)) return FALSE; $r = thread_tid__delete(array('tid' => $tid)); return $r; } function thread_tid_count() { $n = thread_tid__count(); return $n; } // 统计用户主题数 大数量下严谨使用非主键统计 function thread_uid_count($uid) { $n = thread_tid__count(array('uid' => $uid)); return $n; } // 统计栏目主题数 大数量下严谨使用非主键统计 function thread_fid_count($fid) { $n = thread_tid__count(array('fid' => $fid)); return $n; } ?>javascript - Send MongoDB query result as JSON using express - Stack Overflow
最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Send MongoDB query result as JSON using express - Stack Overflow

programmeradmin3浏览0评论

I'm writing an application where I use express, Node.js and MongoDB (using mongojs). I have a module db.js and a server.js, which have the snippets below.

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);
});

It's working because, as you can see, I'm (probably incorrectly) using callback.json(data), when I should be using callback(data). I think the db.js module should not be responsible for sending the response and I should pass res.json as the callback to my function.

The problem is: when I do things the way I consider right, I face the following error:

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 mandHandler (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)

How to properly send the JSON response without sending the response object to my DB module?

P.S. The content of line 36 of db.js, when I make the changes, is callback(data);.

I'm writing an application where I use express, Node.js and MongoDB (using mongojs). I have a module db.js and a server.js, which have the snippets below.

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);
});

It's working because, as you can see, I'm (probably incorrectly) using callback.json(data), when I should be using callback(data). I think the db.js module should not be responsible for sending the response and I should pass res.json as the callback to my function.

The problem is: when I do things the way I consider right, I face the following error:

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 mandHandler (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)

How to properly send the JSON response without sending the response object to my DB module?

P.S. The content of line 36 of db.js, when I make the changes, is callback(data);.

Share Improve this question edited Jan 14, 2016 at 2:17 Amaury Medeiros asked May 13, 2014 at 22:15 Amaury MedeirosAmaury Medeiros 2,2334 gold badges27 silver badges43 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 6

You're right that db.js shouldn't call res or even know about it. It's good to keep it separated.

Following this (untested):

db.js

    var getUsersByCity = function(city, cb) {
        db.users.find({'city': city}).toArray(cb);
    }

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);
            }
        });
    });

Two overall problems I see:

First, your db.js file should do something like:

callback(err, data);

Second, your server.js call should look more like:

db.getUsersByCity(body.city, function(err, data){
    if(err){
        res.send(500, "something went wrong");
    }else{
        res.json(data);
    }
});

The db.getUsersByCity call is asynchronous because you can't read anything until the database call es back on it's callback. I didn't read too much of the error though.. See if that clears things up at all.

发布评论

评论列表(0)

  1. 暂无评论