0

I have the following probelm that elements is undefined when make it equal to a Schema. the element courses in Course.js is undefined.

User.js file:

const mongoose = require("mongoose");

let Course = require(__dirname + "/Course.js");
let Tutor = require(__dirname + "/Tutor.js");

let Schema = mongoose.Schema;

console.log(Course.courseSchema)

var userSchema = new Schema ({
  name: String,
  email: String,
  username: String,
  password: String,
  courses: [Course.courseSchema],
  tutors: [Tutor.tutorSchema],
  isTutor: Boolean,
  subscribed: Boolean,
  googleId: String,
  facebookId: String
});


let User = mongoose.model("User", userSchema);


module.exports = {
  userSchema: userSchema,
  User: User
}

Course.js file:

const mongoose = require("mongoose");

let Schema = mongoose.Schema;

let Tutor = require(__dirname + "/Tutor.js");
let Category = require(__dirname + "/Category.js");
let Module = require(__dirname + "/Module.js");
let User = require(__dirname + "/User.js" );
let CourseReview = require(__dirname + "/CourseReview.js");

var courseSchema = new Schema ({
  title: String,
  categories: [Category.categorySchema],
  tags: [String],
  shortDescription: String,
  students: [User.userSchema],
  language: [String],
  tutor: [Tutor.tutorSchema],
  requirement: String,
  description: String,
  module: [Module.moduleSchema],
  reviews: [CourseReview.courseReviewSchema]
});

let Course = mongoose.model("Course", courseSchema);

module.exports = {
  courseSchema: courseSchema,
  Course: Course
}

dbs file strcuture:

dbs
├── Course.js
├── User.js

Im getting back "TypeError: Invalid value for schema Array path courses, got value "undefined". I'be been trying to fix the directory but the Schema cant be recognized and I ghave read the subdocument documentation that allow you to call the schema in another Schema. Does anybody know how to fix this?

Hoang
  • 69
  • 2
  • 7

1 Answers1

4

You've got circular dependency between User and Courses module. As simple as that - more on this particular issue. that's why Course.courseSchema is undefined while loading User.js.

Additionally, your schema doesn't make practical sense. You probably want to reference these users, courses, tutors by some kind of identifiers thus creating relations. You don't want user.courses contain Course which again contain instance of user and so on.

See this answer for description how to create relationships in mongoose.

Zbigniew Zagórski
  • 1,921
  • 1
  • 13
  • 23
  • Thank for your advice, it actually helps me to restructure my database again to avoid circular dependency – Hoang Jul 03 '20 at 15:28