引用多个集合的集合

时间:2019-03-06 11:18:01

标签: mongodb

我想要一个具有多个引用多个集合的字段的集合,像这样:

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来获取数据,但是看起来它仅适用于集合中的单个字段吗?

有帮助吗?谢谢! :-)

1 个答案:

答案 0 :(得分:1)

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

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')

那样填充它