【问题标题】:Mongoose populate array猫鼬填充数组
【发布时间】:2015-07-01 06:42:02
【问题描述】:

我无法让 mongoose 填充对象数组。

架构如下:

var topOrganisationsForCategorySchema = new mongoose.Schema({
  category: String,
  topOrganisations: [{
    organisation: {
      type: mongoose.Schema.Types.ObjectId,
      ref: 'organisation'
    },
    model: mongoose.Schema.Types.Mixed
  }]
});

module.exports = mongoose.model('topOrganisationsForCategory', topOrganisationsForCategorySchema);

我希望这个集合中的所有对象都填充一组组织。

这是我尝试过的

TopOrganisationsForCategory
  .find()
  .exec(function(err, organisation) {
    var options = {
      path: 'topOrganisations.organisation',
      model: 'organisation'
    };

    if (err) return res.json(500);
    Organisation.populate(organisation, options, function(err, org) {
      res.json(org);
    });
  });

var organisationSchema = new mongoose.Schema({
  name: String,
  aliases: [String],
  categories: [String],
  id: {
    type: String,
    unique: true
  },
  idType: String
});

organisationSchema.index({
  name: 'text'
});

module.exports = mongoose.model('organisation', organisationSchema);

【问题讨论】:

    标签: mongodb mongoose


    【解决方案1】:

    你很接近,但有几点注意事项:

    • 以下代码假设您还拥有Oranisation 的架构/模型声明。
    • 我不确定model 属性是作为选项(无效)还是实际上是topOrganisations 的属性。

    所以,我留下了 model,因为它不会引起任何问题,但请注意,如果您将其用作选项,它不会按照您的想法行事。

    // Assuming this schema exists
    var organisationSchema = new mongoose.Schema({...});
    
    var topOrganisationsForCategorySchema = new mongoose.Schema({
      category: String,
      topOrganisations: [{
        organisation: {
          type: mongoose.Schema.Types.ObjectId,
          ref: 'Organisation' // Model name convention is to begin with a capital letter
        }
        // Is `model` supposed to be for the ref above? If so, that is declared in the
        //  Organisation model
        model: mongoose.Schema.Types.Mixed
      }]
    });
    
    // Assuming these model definitions exist
    var Organisation = mongoose.model('Organisation', organisationSchema);
    var TopOrganisationsForCategory = mongoose.model('TopOrganisationsForCategory', TopOrganisationsForCategorySchema);
    
    // Assuming there are documents in the organisations collection
    
    TopOrganisationsForCategory
      .find()
      // Because the `ref` is specified in the schema, Mongoose knows which
      //  collection to use to perform the population
      .populate('topOrganisations.organisation')
      .exec(function(err, orgs) {
        if (err) {
          return res.json(500);
        }
    
        res.json(orgs);
      });
    

    【讨论】:

    • 我确实有一个名为“组织”的组织架构,但它仍然不起作用。它只返回没有填充对象的集合,只有 id
    • @TJF 你能发布你的模型/模式代码吗?除非存在命名一致性问题,否则这应该可以工作。
    • @TJF 啊。按照惯例,模型名称通常以大写字母开头。在我的示例中,我是,但在您的代码中,您不是。您能否检查模型名称的所有字符串值在定义和 ref 选项中都匹配吗?
    • @TFJ 我不知道为什么这不起作用。如果您已验证组织集合中有匹配的文档,则应该可以。
    猜你喜欢
    • 2014-04-19
    • 2015-07-13
    • 2020-01-30
    • 2016-04-28
    • 2014-11-25
    • 2019-07-17
    • 2015-07-13
    • 2016-10-10
    相关资源
    最近更新 更多