hans001
hans001

Reputation: 143

How to nest schemas in mongoose?

I'm trying to nest schemas using mongoose, but i got stuck and i don't really know why. Here is what i got.

My parent schema

const Comment = require("./Comment");

const BookSchema = new Schema({
  _id: Number,
  comments: [{ comment: Comment }],
  ratings: [{ rate: Number }],
  calculatedRating: Number
});

module.exports = Book = mongoose.model("book", BookSchema);

and child schema


const CommentSchema = new Schema(
  {
    userName: String,
    rating: Number,
    body: String,
    submit_date: {
      type: Date,
      default: Date.now
    }
  },
  { _id: false }
);

module.exports = Comment = mongoose.model("comment", CommentSchema);

And with this setup im getting an error :

"TypeError: Invalid schema configuration: Model is not a valid type at path comment."

I'm considering that i did something wrong with those exports but I'm not sure.

Upvotes: 2

Views: 413

Answers (1)

Felipe Plets
Felipe Plets

Reputation: 7510

Your ./Comment should be:

const CommentSchema = new Schema(
  {
    userName: String,
    rating: Number,
    body: String,
    submit_date: {
      type: Date,
      default: Date.now
    }
  },
  { _id: false }
);

module.exports = CommentSchema;

If you define as a new model as you did then it will create it's own collection and will be a new model instead of a sub document schema.

Upvotes: 1

Related Questions