【问题标题】:Mongoose Random Query issuesMongoose 随机查询问题
【发布时间】:2017-07-21 00:47:49
【问题描述】:

我试图弄清楚为什么我正在编写的猫鼬查询总是返回 null。不是像往常一样 [] 而是 null。

代码如下:

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

所以基本上这里发生的是一个文档_id作为一个数字传入。然后我想抓取一个随机团队文档,其中一个团队在当前用户团队的 300 分以内,并且所有者不等于当前用户,因此他们最终不会挑战自己的团队。

奇怪的是,当我在 mongoCompass 中输入以下查询时,它会返回预期的结果

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

我的 angular 2 提供程序如下所示,用于进行 api 调用。

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

对此的任何帮助将不胜感激,因为我确信我在做一些愚蠢的事情,我只是缺乏使用猫鼬的经验来解决这个问题。

【问题讨论】:

    标签: javascript node.js mongoose mongoose-plugins


    【解决方案1】:

    我未能正确传递变量,因此终点正确地返回了空值或 []。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-01-15
      • 1970-01-01
      • 2016-05-29
      • 1970-01-01
      • 2015-07-08
      • 2018-09-10
      • 2017-09-05
      • 1970-01-01
      相关资源
      最近更新 更多