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 - Optional parameters for MongoDB query - Stack Overflow
最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Optional parameters for MongoDB query - Stack Overflow

programmeradmin5浏览0评论

Let's say I have two events:

{"id":1, "name":"event1"},
{"id":2, "name":"event2"}

And I am writing a REST API to retrieve events. This API takes an optional parameter, id, which if present, returns events specific to that id only, and returns all events if null.

So api/events?id=1 should return event1 only, while api/events will return both event1 and event2. Currently I am using an if-else statement, but this is clearly not scalable if I have more optional parameters. Is there any way to express this as a MongoDB query instead?

Code:

app.get('/api/events', function (req, res) {
    var _get = url.parse(req.url, true).query,
        eventCollection = db.collection('events');

    // Parameters passed in URL
    var page = (_get.page) ? _get.page * 10 : 0,
        org_id = (_get_id) ? parseInt(_get_id) : "";

    if (org_id == "") {
        eventCollection.find({

        }, {
            limit: 10,
            skip: page
        }).toArray(function(err, events) {
            if (!err) {
                res.json(
                    events
                );
            }
        });
    } else {
        eventCollection.find({
            org_id: org_id
        }, {
            limit: 10,
            skip: page
        }).toArray(function(err, events) {
            if (!err) {
                res.json(
                    events
                );
            }
        });
    } 
});

P.S. I am using the Node.js Javascript driver for MongoDB.

Let's say I have two events:

{"id":1, "name":"event1"},
{"id":2, "name":"event2"}

And I am writing a REST API to retrieve events. This API takes an optional parameter, id, which if present, returns events specific to that id only, and returns all events if null.

So api/events?id=1 should return event1 only, while api/events will return both event1 and event2. Currently I am using an if-else statement, but this is clearly not scalable if I have more optional parameters. Is there any way to express this as a MongoDB query instead?

Code:

app.get('/api/events', function (req, res) {
    var _get = url.parse(req.url, true).query,
        eventCollection = db.collection('events');

    // Parameters passed in URL
    var page = (_get.page) ? _get.page * 10 : 0,
        org_id = (_get_id) ? parseInt(_get_id) : "";

    if (org_id == "") {
        eventCollection.find({

        }, {
            limit: 10,
            skip: page
        }).toArray(function(err, events) {
            if (!err) {
                res.json(
                    events
                );
            }
        });
    } else {
        eventCollection.find({
            org_id: org_id
        }, {
            limit: 10,
            skip: page
        }).toArray(function(err, events) {
            if (!err) {
                res.json(
                    events
                );
            }
        });
    } 
});

P.S. I am using the Node.js Javascript driver for MongoDB.

Share Improve this question asked Oct 25, 2013 at 1:47 Wei HaoWei Hao 2,8569 gold badges28 silver badges40 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 14

Single Parameter

One idea would be to set the query object with the ternary operator.

Something like the following:

app.get('/api/events', function (req, res) {
    var _get = url.parse(req.url, true).query,
        eventCollection = db.collection('events');

    // Parameters passed in URL
    var page = (_get.page) ? _get.page * 10 : 0,
        query = (_get_id) ? {org_id:parseInt(_get_id)} : {};

    eventCollection.find(query, {limit: 10, skip: page}).toArray(function(err, events){
        if (!err) {
            res.json(
                events
            );
        }
    });
});

Multiple Parameters

Having that been said, if you have multiple parameters to query, one way would be to build a JSON object like below:

app.get('/api/events', function (req, res) {
    var _get = url.parse(req.url, true).query,
        eventCollection = db.collection('events');

    // Parameters passed in URL
    var page = (_get.page) ? _get.page * 10 : 0,
    query = {};

    (_get_id) ? (query_id = parseInt(_get_id)) : "";
    (_get.name) ? (query.name = _get.name) : "";
    (_get.param3) ? (query.name = _get.param3) : "";

    eventCollection.find(query, {limit: 10, skip: page}).toArray(function(err, events){
        if (!err) {
            res.json(
                events
            );
        }
    });
});

I'll leave it to you to take the block where the query parameters are defined and turn it into a for loop.

Unknown Parameters

If you don't know the number of parameters ahead of time, one option is to build a string and then convert it to a JSON object. However, I don't remend this. It's dangerous to let users define parameters.

发布评论

评论列表(0)

  1. 暂无评论