Jak najít pomocí mongoose dotaz, pokud uživatel je uvnitř pole uživatelů

0

Otázka

Snažím se najít způsob, jak zkontrolovat, zda student podepsal do kurzu/s pomocí mongoose.

Mám tyto schémata:

Samozřejmě schématu:

    const mongoose = require("mongoose");
    const User = require("../models/User");

    const CourseSchema = new mongoose.Schema(
     {
    courseName: { type: String, required: true, unique: true },
    teacher: {
      teacherName: { type: String },
      teacherID: {
        type: mongoose.Schema.Types.ObjectId,
        ref: "User",
      },
    },
    students: [
      {
        studentName: { type: String },
        studentID: {
          type: mongoose.Schema.Types.ObjectId,
          ref: "User",
        },
      },
    ],
    },
      { collection: "courses" },
     { timestamps: true }
     );

    module.exports = mongoose.model("Course", CourseSchema);

Tady jsem šetří všechny studenty, které podepsaly samozřejmě uvnitř studenti pole objektů.

Student schématu:

const mongoose = require("mongoose");

const UserSchema = new mongoose.Schema(
  {
    username: { type: String, required: true, unique: true },
    email: { type: String, required: true, unique: true },
    password: { type: String, required: true },
    userType: {
      type: String,
      enum: ["student", "teacher"],
      default: "student",
    },
    isOnline: { type: Boolean, default: false },
  },
  { collection: "users" },
  { timestamps: true }
);
module.exports = mongoose.model("User", UserSchema);

Teď se snažím vytvořit dotaz, který vrátí seznam předmětů, které student podepsal.

Například:

Pokud budu mít 3 kurzy = [matematika, angličtina, programování] a studenta s id = 1, kteří podepsali (je v studenty array) pro matematiky a angličtiny, pak dotaz vrátí matematiky a kurzy angličtiny.

Zkoušel jsem to bez úspěchu (získání null, ale uživatel je u studentů pole objektů):

router.post("/:id", async (req, res) => {
  try {
    // get user
    var user = await User.findOne({
      username: req.body.username,
      email: req.body.email,
      password: req.body.password,
    });
    // search user courses by user id.
    const coursesList = await Course.find({
      students: {
        $in: [{ studentID: user._id, studentName: user.username }],
      },
    });
    res.status(200).json(coursesList);
  } catch (err) {
    res.status(500).json(err.message);
  }
});
express javascript mongodb mongoose
2021-11-23 19:11:12
2
1

Můžete to udělat to takhle:

const coursesList = await Course.find({ "students.studentID": user._id });

Pracovní příklad

2021-11-23 19:21:04
1

Pokud si jen chcete vrátit odpovídající uživatel, můžete použít agregace potrubí. Živé demo zde

Databáze

[
  {
    "course": "Math",
    "students": [
      {
        studentID: "id_1",
        studentName: "Name 1"
      },
      {
        studentID: "id_2",
        studentName: "Name 2"
      }
    ]
  },
  {
    "course": "English",
    "students": [
      {
        studentID: "id_1",
        studentName: "Name 1"
      },
      {
        studentID: "id_3",
        studentName: "Name 3"
      }
    ]
  },
  {
    "course": "Programming",
    "students": [
      {
        studentID: "id_4",
        studentName: "Name 4"
      },
      {
        studentID: "id_5",
        studentName: "Name 5"
      }
    ]
  },
  
]

Dotaz

db.collection.aggregate([
  {
    $unwind: "$students"
  },
  {
    $match: {
      "students.studentID": "id_1"
    }
  }
])

Výsledek

[
  {
    "_id": ObjectId("5a934e000102030405000000"),
    "course": "Math",
    "students": {
      "studentID": "id_1",
      "studentName": "Name 1"
    }
  },
  {
    "_id": ObjectId("5a934e000102030405000001"),
    "course": "English",
    "students": {
      "studentID": "id_1",
      "studentName": "Name 1"
    }
  }
]
2021-11-23 20:27:18

V jiných jazycích

Tato stránka je v jiných jazycích

Русский
..................................................................................................................
Italiano
..................................................................................................................
Polski
..................................................................................................................
Română
..................................................................................................................
한국어
..................................................................................................................
हिन्दी
..................................................................................................................
Français
..................................................................................................................
Türk
..................................................................................................................
Português
..................................................................................................................
ไทย
..................................................................................................................
中文
..................................................................................................................
Español
..................................................................................................................
Slovenský
..................................................................................................................