简体   繁体   中英

Mongoose Random Query issues

I'm trying to figure out why a mongoose query I'm writing always returns null. Not [] as usual but null.

Here is the code:

// Get random single opponent within 300 points of your team value in either direction
app.get('/api/teams/getOpponent', function (req, res) {
    var value = req.query.teamValue;
    var owner = req.query.owner;
    var maxVal = value + 300;
    var minVal = value - 300;
    var filter = {
        value: { $gte: minVal, $lte:maxVal },
        owner:  { $ne: owner }
    };

    var fields = {}
    var options = { limit: 1 }
    // use mongoose to get all teams in the database
    Team.findRandom(filter, fields, options, function (err, team) {
        // if there is an error retrieving, send the error. nothing after res.send(err) will execute
        if (err)
            res.send(err)
        res.json(team); // return a team in JSON format
    });
});

So basically what happens here is a document _id gets passed in as a well as a number. I then want to grab a random team document where a team is within 300 points of the current user team and where the owner isn't equal to the current user so they don't end up challenging their own team.

Weirdly enough when I enter the below query into the mongoCompass it returns the expected results

{ "value": { $gte:1000, $lte:1600}, "owner": { $ne: "58986cd25e7c780011881bcd" } }

My angular 2 provider looks as follows for making the api call.

getOpponent(options) {
    console.log("options", options);
    return new Promise(resolve => {
        this.http.get('https://pitchlife-hearts.herokuapp.com/api/teams/getOpponent?teamValue=' + options.value + '&owner=' + options.owner)
            .map(res => res.json())
            .subscribe(data => {
                this.data = data;
                resolve(this.data);
            });
    });
}

Any help with this would be hugely appreciated as I'm certain I'm doing something stupid I just lack the experience with mongoose to figure it out.

我无法正确传递变量,因此端点正确返回了空值或[]。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM