mongodb - Mongoose 填充数组

标签 mongodb mongoose

我无法让 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);

最佳答案

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

  • 以下代码假定您还具有 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);
  });

关于mongodb - Mongoose 填充数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31149179/

相关文章:

node.js - 想在mongodb node.JS中通过_id获取引用集合的对象

c# - 更新 mongodb 文档中的特定字段

python - Kedro 与 MongoDB 和其他文档数据库?

node.js - 合并聚合并在 MongoDB 中查找结果

javascript - 密码在保存到数据库之前不会进行哈希处理

node.js - Passport 本地 Mongoose 错误: No Username Was Given

Mongodb:如何查询嵌套文档和顶级文档

node.js - mongodb 集合中的更改

mongodb - Mongo只读同步数据库

node.js - mongodb/mongoose addToSet 将对象添加到具有相同 id 的数组