简体   繁体   中英

Mongoose: Invalid value for schema Array path, got value “undefined”

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM