我正在嘗試找到一種方法來檢查學生是否使用貓鼬簽署了課程。
我有這些模式:
課程架構:
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);
在這里,我將所有簽署課程的學生保存在學生物件陣列中。
學生模式:
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);
現在我正在嘗試進行查詢,該查詢將回傳學生簽署的課程串列。
例如:
如果我有 3 門課程 = [數學、英語、編程] 并且有一個 id = 1 的學生為數學和英語簽名(在學生陣列中),那么查詢將回傳數學和英語課程。
我試過這個沒有成功(得到空值,但用戶在學生物件陣列中):
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);
}
});
uj5u.com熱心網友回復:
你可以這樣做:
const coursesList = await Course.find({ "students.studentID": user._id });
作業示例
uj5u.com熱心網友回復:
如果您只想回傳匹配的用戶,則可以使用聚合管道。現場演示在這里
資料庫
[
{
"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"
}
]
},
]
詢問
db.collection.aggregate([
{
$unwind: "$students"
},
{
$match: {
"students.studentID": "id_1"
}
}
])
結果
[
{
"_id": ObjectId("5a934e000102030405000000"),
"course": "Math",
"students": {
"studentID": "id_1",
"studentName": "Name 1"
}
},
{
"_id": ObjectId("5a934e000102030405000001"),
"course": "English",
"students": {
"studentID": "id_1",
"studentName": "Name 1"
}
}
]
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/364398.html
標籤:javascript 节点.js MongoDB 表达 猫鼬
