外键由多个模型组成

问题描述 投票:0回答:2

我正在使用mongo和mongoose,我正在尝试为我的应用程序建模。 我有以下型号:ProductA,ProductB和ProductChat。 每个产品可以有很多聊天。每次聊天都与唯一的产品(A或B)相关。 我希望ProductChat能够引用相关的产品文档。我考虑过将productType,productId字段添加到ProductChat: const ProductChatSchema = new Schema({ ... ... productType: { type: 'String', required: true, enum: [ 'A', 'B' ] }, product: { type: Schema.Types.ObjectId, required: true, ref: '???' // Ref to what? }, ... ... }); 但是我不知道在'ref'上放什么...... 我想避免在ProductChat上添加productAId,productBId字段,因为可能有很多产品。 知道怎么做才对吗?

javascript node.js mongodb mongoose-schema
2个回答
1
投票

由于有许多产品,请将ProductChat ref提供给数组中的ProductsA(B,C ..)集合。

const productA = new Schema({
    ProductChatIds: [{
        type: Schema.Types.ObjectId,
        ref: 'ProductChat'
    }]
});

const productB = new Schema({
    ProductChatIds: [{
        type: Schema.Types.ObjectId,
        ref: 'ProductChat'
    }]
});

0
投票

ref字段意味着将在哪个集合中提到的id将被搜索。所以,你必须参考这个集合。例如:

var postSchema = new Schema({
    name: String,
    postedBy: {type: mongoose.Schema.Types.ObjectId, ref: 'User'},
    dateCreated: Date,
    comments: [{body:"string", by: mongoose.Schema.Types.ObjectId}],
});

然后制作你的模特:

var Post = mongoose.model('Post', postSchema);
© www.soinside.com 2019 - 2024. All rights reserved.