链条过滤条件动态

时间:2016-03-22 09:33:19

标签: rethinkdb rethinkdb-javascript

如何在RethinkDB中链接多个条件?这就是我现在所得到的,如果我只将live sports作为参数传递,那么该怎么办呢。我通过livesports参数后,sports显然会覆盖filter变量并忽略live参数。

app.get('/bets', function (req, res) {
    var live = req.query.live;
    var sports = req.query.sports;

    var filter = {};

    if (live === undefined) {
        filter = r.or(r.row('live').eq(0), r.row('live').eq(1));
    } else {
        filter.live = parseInt(live);
    }

    if (sports !== undefined) {
        var sports = sports.split(',');
        filter = function (doc) {
            return r.expr(sports).contains(doc("sport"));
        }
    }

    r.table('bets').filter(filter).limit(100).run(connection, function(err, cursor) {
        // ...
    });
});

1 个答案:

答案 0 :(得分:2)

您可以使用RethinkDB链接过滤器。

有些事情(警告,未经测试):

app.get('/bets', function (req, res) {
    var live = req.query.live;
    var sports = req.query.sports;

    var liveFilter, sportFilter;

    if (live === undefined) {
        liveFilter = r.or(r.row('live').eq(0), r.row('live').eq(1));
    } else {
        liveFilter = function (doc) { return true; };
    }

    if (sports !== undefined) {
        sports = sports.split(','); // no need to redefine the variable here
        sportFilter = function (doc) {
            return r.expr(sports).contains(doc("sport"));
        }
    } else {
         sportFilter = function (doc) { return true; };
    }

    r.table('bets')
     .filter(liveFilter)     // apply the first filter
     .filter(sportsFilter)   // apply the second filter
     .limit(100)
     .run(connection, function(err, cursor) {
        // ...
    });
});

或者你可以制作一个过滤功能来处理实时和运动过滤器(同样未经测试,这是为了让你入门):

app.get('/bets', function (req, res) {
    var live = req.query.live;
    var sports = req.query.sports.split(',');

    var filter = function(doc){
      var sportPass, livePass;

        if (live === undefined) {
            livePass = r.or(r.row('live').eq(0), r.row('live').eq(1))(doc);
        } else {
            livePass = parseInt(live); // not sure what you meant by filter.live here
        }

        if (sports !== undefined) {
            sportPass = r.expr(sports).contains(doc("sport"));
        }

        return sportPass && livePass;
    };


    r.table('bets').filter(filter).limit(100).run(connection, function(err, cursor) {
        // ...
    });
});