【问题标题】:mongoose populate nested schema without model猫鼬填充没有模型的嵌套模式
【发布时间】:2019-12-27 21:43:01
【问题描述】:

我正在尝试填充嵌套模式而不为子模式创建模型,但没有任何成功。

我有一个由 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')

有什么想法吗?

【问题讨论】:

    标签: node.js mongodb express mongoose


    【解决方案1】:

    由于填充无法引用子文档数组,因为您有单独的选项架构,为什么不使用它。

    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)
    

    【讨论】:

      猜你喜欢
      • 2021-12-25
      • 2018-06-23
      • 2018-10-15
      • 2019-03-22
      • 2019-05-04
      • 2021-05-16
      • 2015-02-09
      • 2012-10-16
      相关资源
      最近更新 更多