【问题标题】:Mongoose: Set field in schema using search queryMongoose:使用搜索查询在架构中设置字段
【发布时间】:2015-11-25 11:16:47
【问题描述】:

所以.. 我想知道在 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())
});

因此,当我使用查询搜索俱乐部时,我希望填充 playMatches 字段。现在我使用一种“单例类型的方式”来填充 playMatches 字段,如下所示:

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

但是因为我希望事情异步进行,这实际上并不能正常工作,而且我不想在使用任何其他使用 playMatches 字段的函数之前调用一个方法来设置 playMatches 字段。也太丑了吧。。

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

提前谢谢!

【问题讨论】:

  • playMatches 是否存储在不同的集合中?请同时发布您当前使用的代码。
  • 是的,它们存储在集合“matches”中,而俱乐部存储在集合“clubs”中。
  • 能否也发布匹配集合的架构和模型代码?

标签: node.js mongodb mongoose mongoose-populate


【解决方案1】:

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

【讨论】:

  • 感谢您的快速回答!我熟悉填充。但是我似乎无法使用它来完成这项工作。填充总是查看另一个对象的 id。另外,我不想将俱乐部的所有相关 matchIds 放在其对象中。这并没有让事情变得更加灵活。
  • 我理解你想要做什么,我认为你已经以最好的方式实现了它。您也不能定义虚拟字段,因为它们不能是异步的。
  • 该死的!我以前很怕那个!这种方式感觉不对:|。哦,好吧,非常感谢您抽出宝贵时间!
猜你喜欢
  • 1970-01-01
  • 2017-01-13
  • 2016-10-04
  • 2017-09-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-09-16
  • 2017-06-21
相关资源
最近更新 更多