Mongoose 从多个可能的集合中填充 ObjectID

Cad*_*ery 6 mongoose mongodb node.js

我有一个看起来像这样的猫鼬模型

var LogSchema = new Schema({
    item: {
        type: ObjectId,
        ref: 'article',
        index:true,
    },
});
Run Code Online (Sandbox Code Playgroud)

但是 'item' 可以从多个集合中引用。有可能做这样的事情吗?

var LogSchema = new Schema({
    item: {
        type: ObjectId,
        ref: ['article','image'],
        index:true,
    },
});
Run Code Online (Sandbox Code Playgroud)

这个想法是“项目”可以是来自“文章”集合或“图像”集合的文档。

这是可能的还是我需要手动填充?

小智 6

问题很老,但也许其他人仍在寻找类似的问题:)

我在 Mongoose Github 中发现了这个问题:

mongoose 4.x 支持使用refPath而不是 ref:

var schema = new Schema({
  name:String,
  others: [{ value: {type:mongoose.Types.ObjectId, refPath: 'others.kind' } }, kind: String }]
})
Run Code Online (Sandbox Code Playgroud)

在@CadeEmbery 的情况下,它将是:

var logSchema = new Schema({
  item: {type: mongoose.Types.ObjectId, refPath: 'kind' } },
  kind: String
})
Run Code Online (Sandbox Code Playgroud)

不过我还没试过...


Gré*_*EUT 4

首先是一些基础知识

ref选项表示 mongoose 当您使用 时要获取哪个集合的数据populate()

ref选项不是强制的,当你不设置的时候,populate()需要你动态的ref给他使用该model选项。

@例子

 populate({ path: 'conversation', model: Conversation }).
Run Code Online (Sandbox Code Playgroud)

这里你对 mongoose 说 ObjectId 后面的集合是Conversation

不可能给出或数组。populateSchemarefs

其他一些Stackoverflow 的人也问过这个问题。


解决方案 1:填充两者(手动)

尝试填充第一个,如果没有数据,则填充第二个。


解决方案 2:更改架构

创建两个链接,并设置其中之一。

var LogSchema = new Schema({
    itemLink1: {
        type: ObjectId,
        ref: 'image',
        index: true,
    },
    itemLink2: {
        type: ObjectId,
        ref: 'article',
        index: true,
    },
});


LogSchema.find({})
     .populate('itemLink1')
     .populate('itemLink2')
     .exec()
Run Code Online (Sandbox Code Playgroud)