我有一个Mongo集合(表),其中包含以下形式的文档:
{
"tableName": "Items",
"rows": [
{
"label": "row 1 label here",
"items": ["item1", "item2", "item3"]
},
{
"label": "row 2 label here",
"items": ["item4", "item5", "item6"]
}
]
}
我还有另一个集合(Items),其中包含以下形式的文档:
{
"id": "item1",
"name": "Item name",
"code": "XXX-XXXX-XXXX",
"price": 100
}
现在,我希望查询给定表中的所有项,因此我使用以下聚合:
{
"$lookup": {
from: "items",
localField: "rows.items",
foreignField: "id",
as: "rows.items"
}
}
所以我期待所有的"Item1","Item2",…替换为其相应的文件:
{
"tableName": "Items",
"rows": [
{
"label": "row 1 label here",
"items": [
{
"id": "item1",
"name": "Item name",
"code": "XXX-XXXX-XXXX",
"price": 100
},
... // the rest of the items
]
},
... // the rest of the rows
]
}
但是,"row"作为对象返回,只包含预期数组中的第一个对象,标签字段甚至不见了:
{
"tableName": "Items",
"rows": { // <-- rows is returned as on object, should be array
"items": [ // <-- the "label" field is missing
{
"id": "item1",
"name": "Item name",
"code": "XXX-XXXX-XXXX",
"price": 100
},
... // the rest of the items
]
}
}
Edit:以下分别是"行"、"项"和"表"的模式:
const RowSchema = new Schema({
label: String,
items: [String]
}, {
_id: false
})
const ItemSchema = new Schema({
id: String,
name: String,
code: String,
price: Number
}, {
_id: false
})
const TableSchema = new Schema({
tableName: String,
rows: [RowSchema]
})
那么,如何保留外部数组和缺少的字段呢?