3

如何在 RethinkDB 中链接多个条件?这就是我现在得到的,如果我只传递live sports作为参数,它会起作用。一旦我传递了liveandsports参数,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) {
        // ...
    });
});
4

1 回答 1

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) {
        // ...
    });
});
于 2016-03-24T10:28:22.190 回答