我有以下情况:
const Schema = mongoose.Schema
const AttributeSchema = new Schema({
description: {
type: String,
trim: true,
required: true
},
status: {
type: String,
trim: true,
required: true
},
}
);
const AttributeTypeSchema = new Schema({
type: {
type: String,
trim: true
},
values: [AttributeSchema],
status: {
type: String,
trim: true,
required: true
}
},
{ timestamps: true }
);
module.exports = mongoose.model('attributetypes', AttributeTypeSchema)
以及以下型号
const Schema = mongoose.Schema
const ProductSchema = new Schema(
{
name: {
type: String,
trim: true,
},
attributes: [
{
type: {
type: Schema.Types.ObjectId,
ref: 'attributetypes',
},
values: [
{
type: Schema.Types.ObjectId,
ref: 'attributetypes.values',
}
]
}
]
}
如何通过值数组中保存的ID查询 AttributeType 中的值? 我已经尝试过很多猫鼬的居家变化,但无法获得我想要的。
models.Product.find({"values._id":id})
.populate(
{ path: 'attributes',
populate: [{ path: 'type' }, {path: 'values'}]
}).exec()
接近此的地方
AttributeTypes: {
_id: 1234,
type: "Type A",
values: [
{
_id: 9238,
description: "Value 1"
},
{
_id: 9239,
description: "Value 2"
},
{
_id: 9240,
description: "Value 3"
},
]
}
Product: {
name: "Product Name",
attributes: [
{
type: "Type A",
values: [ "Value 1", "Value 3" ]
}
]
}
我想使用mongodb提供的嵌套子文档。顺便说一句,我在我的API顶部使用GraphQL和apollo。