【问题标题】:Collection referencing multiple collections集合引用多个集合
【发布时间】:2019-07-28 01:00:39
【问题描述】:

我想要一个包含多个字段引用多个集合的集合,类似这样:

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

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

【问题讨论】:

  • 真的不知道这里的问题是什么。似乎有一个内置的答案,你期望有人同意你。如果您需要有关如何构建数据的建议,您可以考虑解释您需要实现的目标。
  • @NeilLunn 问题是:如何从这样的集合中获取数据?

标签: mongodb


【解决方案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')一样填充它

【讨论】:

    猜你喜欢
    • 2015-07-11
    • 2013-02-25
    • 2019-02-11
    • 1970-01-01
    • 2015-10-30
    • 1970-01-01
    • 2011-06-21
    • 1970-01-01
    相关资源
    最近更新 更多