我正在使用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字段,因为可能有很多产品。
知道怎么做才对吗?
由于有许多产品,请将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'
}]
});
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);