我创建了一个数据库结构,如下所示。在此结构中,我想检索从当前日期 - 7 天及以后有比赛的联赛。我的问题是,这对于我的数据库的当前结构是否可能,或者我需要在可能之前更改它?
联赛架构
var leagueSchema = new Schema({
name: String,
league: Number
});
匹配架构
var matchSchema = new Schema({
matchId: Number,
leagueId: Number,
date: Date,
homeName: String,
awayName: String,
});
您的设计可以使用一些更改,您可以在其中为 population 创建对其他集合中的文档的引用。 要有效。填充是用其他集合中的文档自动替换文档中指定路径的过程在 matchSchema
中,league
字段设置为数字 _id
,其中 ref 选项告诉 Mongoose 在填充过程中使用哪个模型,在本例中为 League
模型。以下示例演示了架构更改:
var mongoose = require('mongoose'),
Schema = mongoose.Schema;
var leagueSchema = new Schema({
_id: Number,
name: String,
league: Number
});
var matchSchema = new Schema({
_id: Number,
league: { type: Number, ref: 'League' },
date: Date,
homeName: String,
awayName: String
});
var League = mongoose.model('League', leagueSchema);
var Match = mongoose.model('Match', matchSchema);
保存文档时,您只需在引用上分配 _id
值,如以下示例所示:
var premierLeague = new League({ _id: 0, name: 'Premiership', league: 100 });
premierLeague.save(function (err) {
if (err) return handleError(err);
var matchDay = new Date(2015, 10, 7);
var match = new Match({
_id: 1,
date: matchDay,
league: premierLeague._id, // assign the _id from the league
homeName: "Manchester United",
awayName: "West Brom"
});
match.save(function (err) {
if (err) return handleError(err);
// thats it!
});
});
现在进行查询以检索包含当前日期 - 7 天及以后的比赛的联赛,您可以使用查询生成器填充比赛的联赛:
var oneWeekAgo = new Date();
oneWeekAgo.setDate(oneWeekAgo.getDate() - 7);
Match
.find({ "date": { "$gte": oneWeekAgo } })
.populate('league')
.exec(function (err, matches) {
if (err) return handleError(err);
console.log(matches);
});
我是一名优秀的程序员,十分优秀!