繁体   English   中英

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

[英]Mongoose populate ObjectID from multiple possible collections

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

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

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

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

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

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

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

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

mongoose 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
})

不过我还没试过...

首先是一些基础知识

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

ref选项不是强制性的,当你不设置它时, populate()要求你使用model选项动态地给他一个ref

@例子

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

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

不可能populateSchema一个refs数组。

其他一些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()

通过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);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM