Mongodb 猫鼬填充数组

Mongodb 猫鼬填充数组,mongodb,mongoose,Mongodb,Mongoose,我无法让猫鼬填充对象数组 模式如下: var topOrganisationsForCategorySchema = new mongoose.Schema({ category: String, topOrganisations: [{ organisation: { type: mongoose.Schema.Types.ObjectId, ref: 'organisation' }, model: mongoose.Schema.Ty

我无法让猫鼬填充对象数组

模式如下:

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

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

  • 下面的代码假设您也有一个用于
    Oranisation
    的模式/模型声明
  • 我不确定
    model
    属性是作为选项(这将是无效的)还是实际上是
    toorganizations
    的属性
因此,我将
模型
保留在中,因为它不应该引起任何问题,但要注意,如果您将其用作选项,它将而不是执行您可能认为的操作

// 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-Ah。按照惯例,典型的做法是模型名称以大写字母开头。在我的例子中,我是,但在你的代码中,你不是。您能检查一下模型名的所有字符串值在定义和ref选项中是否都匹配吗?@TFJ我不知道为什么这不起作用。如果您已经验证了Organizations集合中有匹配的文档,那么这应该可以工作。