0

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,
}

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

3 Comments

I have added school_name in my course schema but can't figure out what to do next. Please provide more details after what to do after adding the school_name in course schema.
stackoverflow.com/questions/35920733/… discusses creating a compound index with options - does that help?
Yes that surely does.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.