【问题标题】:Is property `ref` necessary when schema field type is `ObjectId` in Mongoose?当模式字段类型为 Mongoose 中的“ObjectId”时,是否需要属性“ref”?
【发布时间】:2018-03-06 17:33:11
【问题描述】:

我有一个示例猫鼬模式,如下所示:

new Schema(
  {
    title: {
      type: String,
    },
    digest: {
      type: String,
    },
    owner: {
      type: ObjectId,
      ref: 'User'
    }
  }
)

我想知道当字段类型为ObjectId 时,属性ref 是必需的,例如owner 字段。

【问题讨论】:

    标签: node.js mongodb mongoose


    【解决方案1】:

    不,不是必要的,但如果你拥有它,你将能够轻松加载引用的实体。 http://mongoosejs.com/docs/populate.html

    Kitten.findOne().populate('owner').exec(function (err, kitten) {
      console.log(kitten.owner.name) // Max
    })
    

    没有ref,它只是一个包含ObjectId的普通字段。

    【讨论】:

    • 是的,没有 ref,你需要在填充时声明模型:{path: 'owner', model: 'User'}。
    • 如果字段引用不同的模型,这可以为您提供更大的灵活性。
    猜你喜欢
    • 1970-01-01
    • 2015-01-17
    • 2018-01-07
    • 1970-01-01
    • 1970-01-01
    • 2020-07-31
    • 2020-05-24
    • 2014-08-07
    • 2020-05-01
    相关资源
    最近更新 更多