【问题标题】:Query documents not defined in a Mongoose model查询未在 Mongoose 模型中定义的文档
【发布时间】:2022-01-22 13:50:12
【问题描述】:

我使用 Intervention 模型上的 Mongoose 的 findById 方法查询名为 interventions 的 Mongo 集合。查询返回关联模型中定义的所有字段。

student 字段也存在于 interventions 集合中。猫鼬没有归还它。据推测,这是因为复杂的student 对象(25-30 个键/值对)未在干预模型中定义。我永远不需要将文档插入到干预模型中。

import mongoose from 'mongoose'

const { Schema } = mongoose

const interventionSchema = new Schema(
  {
    abs_count_excused: { type: Number },
    abs_count_unexcused: { type: Number },
    abs_count_total: { type: Number },
    student_id: { type: Number, required: true }
  }
)

const Intervention = mongoose.model(
  'Intervention',
  interventionSchema,
  'interventions'
)
export default Intervention

是否可以在不在干预模型中定义 student 子文档的情况下检索它?

谢谢。

【问题讨论】:

  • 您是否需要更新student 字段?
  • 不通过干预模型。

标签: mongodb mongoose


【解决方案1】:

我不相信您可以在不以某种方式将其作为 Mongoose 架构的一部分的情况下从 MongoDB 检索值。对于 Mongoose 的 Mixed schema type 来说,这似乎是一个机会。

因为您关心的是要将复杂的student 文档转换为架构,并且您不打算通过Intervention 模型更新它,所以Mixed 架构类型的缺点不适用。因此,您可以将 student 字段添加到您的架构中,如下所示:

const interventionSchema = new Schema(
  {
    abs_count_excused: { type: Number },
    abs_count_unexcused: { type: Number },
    abs_count_total: { type: Number },
    student_id: { type: Number, required: true },
    student: { type: Object }
  }
)

【讨论】:

    猜你喜欢
    • 2019-03-18
    • 2021-06-29
    • 1970-01-01
    • 1970-01-01
    • 2020-07-16
    • 2011-12-08
    • 2015-04-27
    • 2013-07-15
    • 2016-04-28
    相关资源
    最近更新 更多