【问题标题】:Get values from one collection that are used in other (MongoDB)从一个集合中获取在其他集合中使用的值(MongoDB)
【发布时间】:2014-07-29 04:25:25
【问题描述】:

我正在尝试使用 MEAN 堆栈为足球世界杯创建一个小型预测游戏,但我有一个问题,我需要分别获取用户的所有预测游戏以及所有尚未预测的游戏。

我的模式是(用户模式是默认的平均堆栈):

 /** 
 * Prediction Schema
 */
var PredictionSchema = new Schema({
    game_id: {
        type: Schema.ObjectId,
        ref: 'Game'
    },
    user: {
        type: Schema.ObjectId,
        ref: 'User'
    },
    date: {
        type: Date,
        default: Date.now
    },
    choice: {
        type: Number
    }
});

还有游戏架构:

var GameSchema = new Schema({
    team1_key: {
        type: String
    },
    team1_title: {
        type: String
    },
    team2_key: {
        type: String
    },
    team2_title: {
        type: String
    },
    play_at: {
        type: Date
    },
    score1: {
        type: Number
    },
    score2: {
        type: Number
    }
});
mongoose.model('Game', GameSchema);

无论如何,我想要实现的是获得所有预测中提到的所有游戏以及活跃用户。

我试过这样,但它不起作用:

/**
 * List of Games predicted
 */
exports.allPredicted = function(req, res) {
    Game.find({_id: {$in: Prediction.distinct('game_id')}}).sort('-created').populate('user', 'name username').exec(function(err, games) {
        if (err) {
            res.render('error', {
                status: 500
            });
        } else {
            res.jsonp(games);
        }
    });
};

怎么了?我得到了错误:

Error: Failed to lookup view "error" in views directory "/Users/username/Projects/ProjectName/server/views"

有什么想法吗?谢谢! :)

编辑: 有不同的值,不确定这是否是创建方式,但无论如何都有效.. 几乎:

exports.allPredicted = function(req, res) {
    Prediction.distinct('game_id').populate('user', 'name username').exec(function(err, predictions) {
        if (err) {
            res.render('error', {
                status: 500
            });
        } else {
            console.log(predictions);
            Game.find({_id: {$in: predictions }}).sort('-created').populate('user', 'name username').exec(function(err, games) {
                if (err) {
                    res.render('error', {
                        status: 500
                    });
                } else {
                    res.jsonp(games);
                }
            });

        }
    });
};

现在我需要,它也应该考虑活跃用户。有什么帮助吗?

【问题讨论】:

  • Prediction.distinct 是异步调用。

标签: angularjs mongodb express mongoose mean-stack


【解决方案1】:

您可以在 请求用户

那就试试吧

Prediction.find({user : req.user._id}).sort('-created').populate('game_id').exec(function(err, predictions) {
    if (err) {
       res.render('error', {
           status: 500
       });
    } else {
       res.jsonp(predictions);
    }
});

这应该会返回您的用户所做的所有预测,并将 game_id 替换为关联的游戏。

ps:我没有测试它,但我认为这是您正在寻找的请求的逻辑。

ps2:如果您也想填充用户数据,请参阅http://mongoosejs.com/docs/populate.html

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-04-06
    • 2023-03-31
    • 2020-05-13
    • 2014-11-27
    • 1970-01-01
    • 2017-04-03
    • 2018-05-30
    • 1970-01-01
    相关资源
    最近更新 更多