I created a ProductSchema which is extended by a CategorizedProductSchema. The difference between them is that the CategorizedProductSchema has an attribute category which is of type CategorySchema. However, when I create and save a categorized product, it does not save the category information, it only saves the fields in the ProductSchema.
Here is the full definition for the schema
import mongoose from 'mongoose'
const options = { _id:false, discriminatorKey: 'kind' };
export interface Product {
id: String,
productId: String,
productName: String,
productType: String
}
export interface CategorizedProduct extends Product{
categoryFacts: {
description: String,
categoryClass: String
}
}
export interface CategoryProduct {
category: CategorizedProduct
}
const CategorySchema = new mongoose.Schema({
categoryFacts: {
description: String,
categoryClass: String
}
}, options
)
export const ProductSchema = new mongoose.Schema(
{
_id: String,
productCode: String,
productName: String,
productType: String
},
options
)
export const CategorizedProductSchema =
ProductSchema.discriminator('CategorizedProduct',CategorySchema)
export interface ProductDocument extends Product, Document {
}
export interface CategorizedProductModel extends CategorizedProduct, Document {
}
export const ProductModel = mongoose.model<ProductDocument>('products', ProductSchema)
export const CategorizedProductModel = mongoose.model<CategorizedProductModel>.
('products', CategorizedProductSchema)
ProductSchema.index({ productId: 1, productName: 1, productType: 1 }, { unique: true })
ProductSchema.index({ clientHoldId: 1 }, { unique: true })
CategorizedProductSchema.index({ productId: 1, productName: 1, productType: 1 }, { unique: true })
async function saveCategorizedProduct(product:CategorizedProduct){
const result = await CategorizedProductModel.create(product)
}
//results in collection products
/**
*
* _id: "prod-2223",
* productCode: 'ABC'
* productName: 'Watch',
* productType: 'AD-TYPE'
*/
There are no errors reported and the test Categorized product is saved to the database. What am I not doing right? Any help would be appreciated