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

时间:2016-11-15 23:06:55

标签: node.js mongodb mongoose

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

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

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

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

这个想法是'项目'可以是文章中的文件'收集或'图像'集合。

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

3 个答案:

答案 0 :(得分:1)

首先是一些基础知识

ref选项表示mongoose在您使用populate()时获取数据的集合。

ref选项不是强制性的,如果您未设置,populate()要求您使用{动态ref向他提供model {1}}选项。

<强> @example

 populate({ path: 'conversation', model: Conversation }).

在这里你说猫鼬后面的集合是Conversation

无法populateSchema提供refs数组。

其他一些人Stackoverflow people询问了这件事。

解决方案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()

答案 1 :(得分:0)

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

我在猫鼬 Github 中发现了以下问题:

  

猫鼬4.x支持使用 refPath 代替ref:

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

在@CadeEmbery情况下为:

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

但是我还没有尝试过...

答案 2 :(得分:0)

通过 refPath 的动态引用

Mongoose 还可以根据文档中某个属性的值从多个集合中进行填充。假设您正在构建一个用于存储评论的模式。用户可以对博客文章或产品发表评论。

  body: { type: String, required: true },
  on: {
    type: Schema.Types.ObjectId,
    required: true,
    // Instead of a hardcoded model name in `ref`, `refPath` means Mongoose
    // will look at the `onModel` property to find the right model.
    refPath: 'onModel'
  },
  onModel: {
    type: String,
    required: true,
    enum: ['BlogPost', 'Product']
  }
});

const Product = mongoose.model('Product', new Schema({ name: String }));
const BlogPost = mongoose.model('BlogPost', new Schema({ title: String }));
const Comment = mongoose.model('Comment', commentSchema);