所以..我想知道在猫鼬中我是否可以做这样的事情:
var Match = require('./models/Match);
ClubSchema = new mongoose.Schema({
_id: {type: String, required: true, unique: true},
name: {type: String, required: true, unique: true},
playedMatches: //Search query for played matches here (so like Match.find())
});
因此,当我使用查询搜索俱乐部时,我希望填充 playMatches 字段。现在我使用一种“单例类型方式”来填充playedMatches字段,如下所示:
ClubSchema.playedMatches = null;
ClubSchema.methods.setPlayedMatches = function (callback) {
var self = this;
Match.find({$or: [{homeClub: self._id}, {awayClub: self._id}], matchOver: true}).sort({playDate: 'asc'}).exec(function (err, matches) {
if (err) {
callback(err);
} else {
self.playedMatches = matches;
callback(false, matches);
}
});
};
ClubSchema.methods.getPlayedMatches = function (callback) {
if (!this.playedMatches) {
this.setPlayedMatches(function (err, matches) {
if (err) {
callback(err);
} else {
callback(false, matches);
}
});
} else {
callback(false, this.playedMatches);
}
};
但是因为我希望事情变得异步,这实际上不起作用,而且我不想在使用任何其他使用playedMatches字段的函数之前调用一个方法来设置playedMatches字段,因为这很丑。也..
MatchSchema 如下所示:
var MatchSchema = new mongoose.Schema({
_id: {type: String, required: true, unique: true},
homeClub: {type: String, ref: 'Club'},
awayClub: {type: String, ref: 'Club'},
playDate: {type: Date, required: true},
goalsHomeClub: {type: Number},
goalsAwayClub: {type: Number},
matchOver: {type: Boolean, default: false}
});
提前谢谢!