0

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 missing the category field
   /**
    * 
    *     _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

1 Answer 1

0

I used the ProductSchema instead of creating a ProductModel and then use that for creating the CategorizedProduct from the model.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.