簡體   English   中英

mongoDB 中的多對多關系

[英]Many to many relation in mongoDB

我的 nosql 數據庫(mongoDB 和 mongoose.js)中有兩個模型: UserClass

每個 class 有一名教師和多名學生(教師和學生是用戶模型)。

每個用戶可以有很多類。

實現數據庫的最佳解決方案是什么?

我認為在Class model 中包含user_id數組和在用戶class_id中包含 class_id 數組是最好的,對嗎?

假設教師用戶不能作為學生,學生用戶也不能作為教師。

您可以在架構中使用 mongoose 的ref (請參閱 文檔)。 例如:

const UserSchema =  new mongoose.Schema({
    firstName: String,
    lastName: String,
    // other properties you want to define
    classes: [
        {
            type: mongoose.Schema.Types.ObjectId,
            ref: "Class"
        }
    ]
})

const ClassSchema =  new mongoose.Schema({
    className: String,
    // other properties you want to define
    users: [
        {
            type: mongoose.Schema.Types.ObjectId,
            ref: "User"
        }
    ]
})

稍后在查詢數據庫時,您可以使用 mongoose 的填充來自動獲取引用的文檔,而不僅僅是文檔的 id:

User.findById(userId).populate("classes");
Class.findById(classId).populate("users");

這是一個很好的教程,它更詳細地解釋了它: https://bezkoder.com/mongodb-many-to-many-mongoose/

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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