Mongoose:使用搜索查询在模式中设置字段

时间:2015-08-31 12:10:55

标签: node.js mongodb mongoose mongoose-populate

所以..我想知道在Mongoose中我是否能做到这样的事情:

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

所以我希望在使用查询搜索俱乐部时填充playbackMatches字段。现在我使用一种“Singleton类型的方式”来填充playingMatches字段,如下所示:

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

但是因为我希望事情变得异步而不能真正起作用,我不想在使用任何其他使用了playsMatches字段的函数之前调用一个方法来设置playingMatches字段。那也很丑..

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

Thnx提前!

1 个答案:

答案 0 :(得分:2)

Mongoose有一种内置方式,名为populate

您需要做的就是在字段规范的ref字段中提及模型名称。模型名称必须与Mongoose.model方法中的名称相同。

ClubSchema = new mongoose.Schema({
  _id: {type: String, required: true, unique: true},
  name: {type: String, required: true, unique: true},
  playedMatches: [{type: ObjectId, ref: 'Match'}]
});

现在,您可以使用以下代码在查询后自动填充字段中的匹配项:

Club.find({}).populate('playedMatches');