使用Mongoose引用具有未知模型types的对象

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

例如,我有模型:照片,评论,提交,post等,我想有一个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 填充方法的好处吗?

有两种方法可以采取。

1.调用填充时传入ref的值

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

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

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

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

基于dynamic引用部分。

您需要首先将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而不是refdynamic引用。

然后,当你调用populate ,你会做一些事情,比如:

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

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