【问题标题】:MongoDB / Mongoose has many RelationshipMongoDB / Mongoose 有很多关系
【发布时间】:2015-04-07 01:13:42
【问题描述】:

所以我试图弄清楚 Mongo/Mongoose 中的人口和关系。我有一个有很多预测的夹具。如果我想显示一个预测的夹具,我可以简单地使用 populate 方法,但是如果我需要显示一个夹具的所有预测呢?

这听起来很简单,但也许我仍然有我的 SQL 头脑试图弄清楚它。这很容易做到还是我以错误的方式接近它?这是我的模型 -

var FixtureSchema = new Schema({
homeTeam: {
    type: Number,
    required: true,
    ref: 'Team'
},
awayTeam: {
    type: Number,
    required: true,
    ref: 'Team'
},
date: {
    type: Date
},
matchday: {
        type: Number,
        required: true
}
});

var PredictionSchema = new Schema({
goalsHomeTeam: {
    type: Number,
    required: true
},
goalsAwayTeam: {
    type: Number,
    required: true
},
fixture: {
    type: Number,
    ref: 'Fixture'
},
user: {
    type: Schema.ObjectId,
    ref: 'User'
}
});

【问题讨论】:

    标签: node.js mongodb mongoose


    【解决方案1】:

    您必须首先找到您想要的赛程,然后搜索您的预测并找到匹配项。 Mongo 没有“反向”种群,但编写自己的种群很容易:

    Prediction.find({fixture: fixture._id}, function(err, predictions) {
        //do things with predictions
    })
    

    【讨论】:

    • 感谢格兰特。我的问题是,如果我想检索一组灯具并填充所有灯具的所有预测怎么办?这可能吗?
    • 没有真正简单快捷的方法来做到这一点。您不能“填充”,因为夹具不存储对其所有预测的引用。您可以填充 _id 的数组,但这需要您在每次创建新预测时更新夹具对象。另一个可能的解决方案是async library。特别是“每个”功能。遍历fixtures,并为每一个,找到所有Predictions并返回数组。
    • 好的,很好。我相信这会解决我的问题。感谢您的帮助格兰特。
    猜你喜欢
    • 2014-01-21
    • 2014-08-15
    • 2015-05-20
    • 2020-06-12
    • 2015-10-25
    • 2014-09-25
    • 2019-02-01
    • 2013-04-02
    • 2014-07-10
    相关资源
    最近更新 更多