[英]Mongoose: How to extract arrays in subdocuments to a single array in the parent document
使用 Mongoose 的 Express 服務器在其路由之一中從數據庫返回以下 JSON:
{
"gradeLevel": 12,
"classes": [
{
"className": "A",
"students": [
"student1", "student2","student3"
]
},
{
"className": "B",
"students": [
"student4", "student5","student6"
]
},
{
"className": "C",
"students": [
"student7", "student8","student9"
]
}
]
}
在客戶端,我希望能夠例如有效地檢查學生是否在父文檔中的任何類子文檔中。 以下是我構想的解決方案,但不確定哪個是最佳實踐:
students
字段。我也遇到了這個問題。 但是要解決這個問題,您需要一個名為allStudents
的單獨集合,例如它的架構如下{ nameOfStudent: 'String' className: 'String' }
然后將其與子文檔相應地聚合。 因此,無論您將新學生推入allStudents
並提到className
,它將被推入相應 className 的allStudents
子文檔。
用點符號查詢,比如
.find({"classes.students":"student8"})
將檢查classes
數組中每個對象的students
字段,返回包含任何班級中特定學生的文檔。
感謝您提供的答案。 只是使用 vanilla Javascript 共享另一個解決方案,可能對類似情況的人有用:
checkStudent = (batch, student) => {
let result = null
const inClass = (cls) => {
if (cls.students.includes(student)) {
result = cls
return true
}
return false
}
batch.classes.some(inClass)
return result
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.