简体   繁体   中英

how to find using mongoose query if user is inside an array of users

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

You can do it like this:

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

Working example

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM