首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >引用多个集合的集合

引用多个集合的集合
EN

Stack Overflow用户
提问于 2019-03-06 19:18:01
回答 1查看 213关注 0票数 0

我希望有一个包含多个字段引用多个集合的集合,如下所示:

代码语言:javascript
复制
var comboSchema = new Schema({
  oneId: { type: Schema.Types.ObjectId, ref: "One" },
  twoId: { type: Schema.Types.ObjectId, ref: "Two" },
  threeId: { type: Schema.Types.ObjectId, ref: "Three" },
  components: {
    id: {type: Schema.Types.ObjectId, ref: "Component"},
    amount: {type: Number}
  }
}  

我知道我可以使用$lookupaggregate来获取数据,但它看起来只适用于集合中的单个字段?

有什么帮助吗?谢谢!:-)

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-03-06 19:24:28

这是一个使用ref的模型示例,对象中的ref键将采用您正在引用的模型的名称

代码语言:javascript
复制
const mongoose = require('mongoose');
const postSchema = mongoose.Schema({
    text: {
        type: String,
        required: 1
    },
    mediatype: {
        type: String,
        required: 1
    },
    media: {
        type: String,
        required: true
    },
    user: {
        type: mongoose.Schema.Types.ObjectId,
        ref: 'user'
    },
    likes: {
        type: [{
            userid: {
                type: mongoose.Schema.Types.ObjectId,
                ref: 'user'
            }
        }]
    },
    comments: {
        type: [{
            userid: {
                type: mongoose.Schema.Types.ObjectId,
                ref: 'user'
            },
            comment: String
        }]
    },
}, {
    timestamps: true
})

const Post = mongoose.model('post', postSchema)

module.exports = Post

这样您就可以像Post.find().populate('user')一样填充它

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/55021810

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档