簡體   English   中英

Mongoose:如何將子文檔中的數組提取到父文檔中的單個數組

[英]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"
      ]
    }
  ]
}

在客戶端,我希望能夠例如有效地檢查學生是否在父文檔中的任何類子文檔中。 以下是我構想的解決方案,但不確定哪個是最佳實踐:

  1. 當學生被推送到班級子文檔時,也將學生推送到父母的students字段。
  2. 在模型的 toJSON 轉換中添加一個新字段以編譯所有學生。
  3. 在客戶端使用 vanilla Javascript 提取所有學生

我也遇到了這個問題。 但是要解決這個問題,您需要一個名為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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM