【发布时间】:2021-07-22 13:05:32
【问题描述】:
我有一个对象types。它包含多个模式。我需要通过 id 找到一个项目,但该项目可能在 exampleOne 或 exampleTwo 中(注意:将使用两个以上的模式)。
例如,在此查询"id: 608a5b290e635ece6828141e":
{
"_id": "608642db80a36336946620aa",
"title": "titleHere",
"types": {
"exampleOne": [
{
"_id": "6086430080a36336946620ab",
"front": "front",
"back": "back"
},
{
"_id": "608a5b186ee1598ac9c222b4",
"front": "front2",
"back": "back2"
}
],
"exampleTwo": [
{
"_id": "608a5b290e635ece6828141e", // the queried document
"normal": {
"front": "2front",
"back": "2back"
},
"reversed": {
"front": "2frontReversed",
"back": "2backReversed"
}
},
{
"_id": "608a5b31a3f9806de2537269",
"normal": {
"front": "2front2",
"back": "2back2"
},
"reversed": {
"front": "2frontReversed2",
"back": "2backReversed2"
}
}
]
}
}
应该返回:
{
"_id": "608a5b290e635ece6828141e",
"normal": {
"front": "2front",
"back": "2back"
},
"reversed": {
"front": "2frontReversed",
"back": "2backReversed"
}
},
理想情况下,解决方案只需要一次搜索。我对此进行了一些研究,但无法弄清楚如何搜索 types 中的所有对象,而不为每个架构创建搜索并查看其中是否有任何返回结果。
如果需要,这是我的架构:
var MainSchema = new Schema ({
title: { type: String, required: true, maxlength: 255 },
types: {
exampleOne: [exampleOneSchema],
exampleTwo: [exampleTwoSchema],
}
});
var exampleOneSchema = new Schema({
front: {type: String, required: true},
back: {type: String, required: true},
});
var exampleTwoSchema= new Schema({
normal: {
front: {type: String, required: true},
back: {type: String, required: true},
},
reversed: {
front: {type: String, required: true},
back: {type: String, required: true},
},
});
感谢所有帮助!
谢谢,
Sour_Tooth
【问题讨论】:
标签: javascript mongodb mongoose mongodb-query aggregation-framework