BeHappy
BeHappy

Reputation: 3988

Many to many relation in mongoDB

I have two models in my nosql database(mongoDB and mongoose.js): User and Class.

Each class has one teacher and many students (teacher and students are User model).

and each user could have many classes.

What is the best solution for implementing database?

I think having array of user_id inside Class model and array of class_id in User model is best, am I right?

assume teacher user can not be as student and student user can not be as teacher, too.

Upvotes: 0

Views: 148

Answers (1)

eol
eol

Reputation: 24565

You can use mongoose's ref (see the docs) in your schemas. E.g:

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

Later when querying the DB you can use mongoose's populate to automatically get the referenced documents, instead of just the document's id:

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

Here's a nice tutorial, that explains it in further detail: https://bezkoder.com/mongodb-many-to-many-mongoose/

Upvotes: 3

Related Questions