Home > front end >  Mongo Db Unique Constraint issue
Mongo Db Unique Constraint issue

Time:12-01

Developing ERP system for schools. So i have SCHOOL Schema and inside which i have referenced COURSE Schema. What i wanted to do is to have some fields inside COURSE schema unique like course name inside particular school. But if i mark the fields unique in schema itself it will cause problems.

One school can have multiple courses but the name of courses should be unique for that particular school. But two different schools can have courses with same name. eg:- school A has btech so school A can't have other course document with same name but school B can have course with the name btech.

If i make the course_name field unique in schema itself i can't add course_name which has been added in some other school already.

I can make this happen by fetching the db and then checking the course_name one-by-one. But i think that would not be the ideal solution.

Please let me know of some better solutions

I using MONGO DB.

//SCHOOL SCHEMA
const SchoolSchema = 
mongoose.Schema({
 course: [{ type:
 mongoose.Schema.Types.ObjectId,
    ref: 'course'
 }]
})

//Course Schema
const CourseSchema = 
 mongoose.Schema({course_name: {
    type: String,
}

CodePudding user response:

In order to have the database enforce uniqueness on the school course_name combination, both fields will need to be in the same collection.

The simplest way would be to include the school name or _id in the course schema.

  • Related