【问题标题】:Mongoose: Populate referenced SubDocumentMongoose:填充引用的子文档
【发布时间】:2019-01-08 10:57:18
【问题描述】:

我有以下架构:

引用 CostCenter 子文档能力中的能力的事件。

const OccurrenceSchema = new mongoose.Schema({
  date: {
    type: Date,
    default: Date.now,
  },
  competence: {
    type: mongoose.Schema.Types.ObjectId,
    ref: 'CostCenter.competences',
  },
  ...
})

CostCenter,我有一个子文档数组,可以通过 Occurence 引用。

const CostCenterSchema = new mongoose.Schema({
  name: {
    type: String,
    required: true,
    trim: true,
  },
  competences: [CompetenceSchema],
});

最后是能力。

const CompetenceSchema = new mongoose.Schema({
  name: {
    type: String,
    required: true,
    trim: true,
  },
});

当我尝试填充权限时,我得到“架构尚未注册模型 \"CostCenter.competences\"。\n使用 mongoose.model(name, schema)”。

const occurrence_list = (request, response) => {
  Occurrence.find()
    .populate('occurrence origin tag entity method priority competence')
    .then(occurrences => response.send(occurrences))
    .catch(e => response.send(e));
};

在引用子文档时如何填充事件?

【问题讨论】:

    标签: node.js mongodb express mongoose


    【解决方案1】:

    首先,您需要将您的 Occurrence 模型更改为此

    const OccurrenceSchema = new mongoose.Schema({
       date: { type: Date, default: Date.now },
       competence: { type: mongoose.Schema.Types.ObjectId, ref:'CostCenter' }
    });
    mongoose.model('Occurrence', OccurrenceSchema);
    

    和 CostCenter 模型:

    const CostCenterSchema = new mongoose.Schema({
       name: { type: String, required: true, trim: true },
       competences:[{ type: mongoose.Schema.Types.ObjectId, ref: 'Competence' }],
    });
    mongoose.model('CostCenter', CostCenterSchema);
    

    最终能力模型:

    const CompetenceSchema = new mongoose.Schema({
       name: { type: String, required: true, trim: true }
    });
    mongoose.model('Competence', CompetenceSchema);
    

    要从 Occurrence 填充权限,您可以这样做:

    Occurrence.find({ your_query })
    .populate('competence')
    .then(occurrences => response.send(occurrences))
    .catch(e => response.send(e));
    

    希望对你有帮助!

    【讨论】:

    • 但是通过这样做,我不再有一个权限子文档,而是一个他们自己集合的权限数组(objectId),对吧?有什么办法可以按照我想要的方式进行吗?提前致谢。
    • 我不明白你想要达到什么目的。你能先试试看结果是不是你想要的吗?如果没有,你能举个例子说明你想要什么
    • 我已经测试过了,我相信这正是我想要的。基本上,我希望拥有具有一系列独特能力的成本中心。这些能力不需要存储在集合中,因此我将它们作为子文档。通过获得一个事件,我希望能够用它的名称填充该事件。我是 Mongo 的新手,所以我很抱歉解释不好,我可能做错了,但我不完全确定。
    • 很高兴听到你想要的。如果您还有任何问题,请告诉我。如果你想了解更多关于 MongoDB 的信息,这是一个很好的开始udemy.com/mongodb-essentials-m,请把我的答案标记为你的答案,这样我可以得到一些积分:)))
    • 我的意思是“不是真的”,你能看完我说的其余部分并告诉我你的想法吗?也许我试图做的不是最好的解决方案,而你的解决方案是让我知道。而且当然! :)
    猜你喜欢
    • 2017-01-27
    • 1970-01-01
    • 2014-08-16
    • 2013-07-08
    • 2017-03-21
    • 2017-06-06
    • 2018-08-16
    • 2014-08-06
    • 1970-01-01
    相关资源
    最近更新 更多