猫鼬填充没有模型的嵌套模式

时间:2019-08-22 14:20:53

标签: node.js mongodb express mongoose

我试图在不为子模式创建Model的情况下填充嵌套模式,但没有成功。

我有一个“问题”模型,该模型由2个模式(问题,选项)创建。

const Option = new mongoose.Schema({
  value: { type: String, required: true }
})

const Question = new mongoose.Schema({
  content: { type: String, required: true },
  options: [Option]
})

module.exports = mongoose.model('Question', Question)

我有一个“评论”模型

const Review = new mongoose.Schema({
  results: [
    {
      question: { type: mongoose.Schema.Types.ObjectId, ref: 'Question' },
      option: { type: mongoose.Schema.Types.ObjectId, ref: 'Question.options' }
    }
  ],
  critical: { type: Boolean, default: false }
})

module.exports = mongoose.model('Review', Review)

好吧,我想创建API / reviews来评论文档的响应数组,但要填充问题和选项。

我尝试了此命令,但是它不起作用。

Model.find({}).populate('results.option')

有什么主意吗?

1 个答案:

答案 0 :(得分:0)

由于您拥有单独的Option模式,因此填充时无法引用子文档数组,为什么不使用它。

const Review = new mongoose.Schema({
  results: [
    {
      question: { type: mongoose.Schema.Types.ObjectId, ref: 'Question' },
      option: { type: mongoose.Schema.Types.ObjectId, ref: 'Option' }
    }
  ],
  critical: { type: Boolean, default: false }
})

module.exports = mongoose.model('Review', Review)