【问题标题】:Referencing an object with an unknown model-type with Mongoose使用 Mongoose 引用具有未知模型类型的对象
【发布时间】:2015-09-15 03:23:28
【问题描述】:

使用Mongoose,当该文档的模型/类型未知时,是否可以有一个引用另一个对象的字段?

例如,我有模型:照片、评论、提交、帖子等,我想要一个引用它们的 Like 模型:

var Like = new Mongoose.Schema({
  // What would the value of `ref` be, should it just be left out?
  target: { type: Schema.Types.ObjectId, ref: '*' }
});

据我了解,ref 需要成为模型。我可以把它放在一起,但这样我还能从 Mongoose 的populate method 中受益吗?

【问题讨论】:

    标签: javascript node.js mongodb mongoose


    【解决方案1】:

    您可以采取两种方法。

    1。调用populate时传入ref的值

    基于Populating across Databases 部分。当您调用populate 时,您可以指定您要使用的模型。

    Like.find().populate({
      path: 'target',
      model: 'Photo'   
    })
    

    这要求您在填充之前知道您想要的模型。

    2。将 ref 的值与目标一起存储

    基于Dynamic References部分。

    您需要先将target 调整为类似于以下内容:

    var Like = new Mongoose.Schema({
      target: {
        kind: String,
        item: {
          type: Schema.Types.ObjectId,
          refPath: 'target.kind'
        }
      }
    });
    

    target.kind 是用于populate 的“ref”值,target.item 是 ObjectId。我们使用refPath 而不是ref 进行动态引用。

    然后,当您致电populate 时,您将改为执行以下操作:

    Like.find().populate('target.item')
    

    请注意,我们填充的是'target.item',而不仅仅是'target'

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-04-03
      • 2018-07-15
      • 1970-01-01
      • 1970-01-01
      • 2015-11-09
      • 2020-03-20
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多