0

所以..我想知道在猫鼬中我是否可以做这样的事情:

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

提前谢谢!

4

1 回答 1

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');
于 2015-08-31T12:27:57.317 回答