首页 文章

Mongoose填充数组

提问于
浏览
2

我不能让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 因为它不应该引起任何问题,但要注意,如果你使用它作为一个选项它是 not 做你可能认为它是什么 .

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

相关问题