Mongoose populate数组

3

我无法让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);
1个回答

0
你接近了,但有几点需要注意:
  • 以下代码假设你还有一个关于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);
  });

1
我有一个名为“organisation”的组织架构模式,但它仍然无法正常工作。它只返回集合而没有填充对象和ID。 - TJF
@TJF,你能否发布你的模型/架构代码?除非存在命名一致性问题,否则这应该可以工作。 - Jason Cust
@TJF 啊。按照惯例,模型名称通常以大写字母开头。在我的示例中是这样的,但在您的代码中不是。您能否检查模型名称的所有字符串值是否在定义和 ref 选项中都匹配? - Jason Cust
@TFJ 我不知道为什么这个不起作用。如果您已验证组织集合中有匹配的文档,那么这应该可以解决问题。 - Jason Cust

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接