user8463989
user8463989

Reputation: 2459

How to embed schema

I want to embed a category schema inside the product schema which effectively would just be the Object ID and title.

My category model:

const categorySchema = new mongoose.Schema({
  name: {
    type: String,
    required: true,
    minlength: 5,
    maxlength: 255
  }
});

const Category = mongoose.model("Category", categorySchema);

module.exports.categorySchema = categorySchema;
module.exports = Category;

Product model:

const { categorySchema } = require("./categoryModel");

const productSchema = new mongoose.Schema({
  name: {
    type: String,
    required: true,
    minlength: 5,
    maxlenth: 255
  },
  description: {
    type: String,
    required: true,
    minlength: 5,
    maxlength: 255
  },
  price: {
    type: Number,
    required: true,
    min: 0
  },
  category: {
    type: categorySchema,
    required: true
  },
});

const Product = mongoose.model("Product", productSchema);

module.exports = Product;

The error I am getting in console is:

TypeError Invalid value for schema path category.type

If I console.log() out categorySchema I get the following:

Schema {
  obj: {
    name: {
      type: [Function: String],
      required: true,
      minlength: 5,
      maxlength: 255
    }
  },
  paths: {
    name: SchemaString {
      enumValues: [],
      regExp: null,
      path: 'name',
      instance: 'String',
      validators: [Array],
      getters: [],
      setters: [],
      options: [Object],
      _index: null,
      isRequired: true,
      requiredValidator: [Function],
      originalRequiredValue: true,
      minlengthValidator: [Function],
      maxlengthValidator: [Function],
      [Symbol(mongoose#schemaType)]: true
    },

Upvotes: 0

Views: 161

Answers (1)

Ravi Shankar Bharti
Ravi Shankar Bharti

Reputation: 9268

Instead of

category: {
    type: categorySchema,
    required: true
}

use

category : categorySchema

Also, it looks like there is a mistake in your export.

Try changing it to this :

module.exports = {
    Category : Category,
    categorySchema : categorySchema
}

Upvotes: 1

Related Questions