1

I'm trying to find a way to check if a student is signed to a course/s using mongoose.

I have these schemas:

Course schema:

    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);

In here I'm saving all of the students that signed the course inside students array of objects.

Student schema:

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);

Now I'm trying to make a query that will return a list of courses which the student signed for.

For example:

If I have 3 courses = [math, English, programming] and a student with id = 1 who signed (is in students array) for math and English, then the query will return math and English courses.

I've tried this without success (getting null, but user is in students array of objects):

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);
  }
});

2 Answers 2

1

You can do it like this:

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

Working example

Sign up to request clarification or add additional context in comments.

Comments

1

If you only want to return the matched user, you could use the aggregation pipeline. Live demo here

Database

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

Query

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

Result

[
  {
    "_id": ObjectId("5a934e000102030405000000"),
    "course": "Math",
    "students": {
      "studentID": "id_1",
      "studentName": "Name 1"
    }
  },
  {
    "_id": ObjectId("5a934e000102030405000001"),
    "course": "English",
    "students": {
      "studentID": "id_1",
      "studentName": "Name 1"
    }
  }
]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.