使用 Mongoose 引用具有未知模型类型的对象 [英] Referencing an object with an unknown model-type with Mongoose

查看:97
本文介绍了使用 Mongoose 引用具有未知模型类型的对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Using Mongoose is it possible to have a field that references another object, when the model/type of that document is unknown?

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

For example, I have the models: Photos, Comments, Submissions, Posts, etc., and I would like to have a Like model that refers back to them:

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 方法中受益 那样?

From what I understand, ref needs to be a Model. I could leave it out all together, but would I still get the benefit of the Mongoose's populate method that way?

推荐答案

您可以采取两种方法.

基于跨数据库填充.当您调用 populate 时,您可以指定要使用的模型.

Based on the section Populating across Databases. When you call populate, you can specify the model you want to use.

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

这要求您在填充之前了解所需的模型.

This requires that you know the model you want before you populate.

基于动态参考部分.

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

You need to first adjust the target to something similar to the following:

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.

target.kind is the value of "ref" that will be used for populate, and target.item is the ObjectId. We use refPath instead of ref for dynamic references.

然后,当您调用 populate 时,您将执行以下操作:

Then, when you call populate, you will instead do something like:

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

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

Note that we populate 'target.item' as opposed to just 'target'.

这篇关于使用 Mongoose 引用具有未知模型类型的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆