Home > Software design >  How to use Map to define a mongoose schema
How to use Map to define a mongoose schema

Time:10-04

I have a product schema that I want to store in MongoDb as a map. The productId is a string value. I checked the Mongoose documentation but do not fully understand the example using map. In currently have it as an array but I really want to store it as a map. Here is my schema:

        const ProductSchema = new mongoose.Schema({
          productId: {type:String, required:true},
          name: String,
          category: String,
          code: Number,
       })

       const ProductsSchema = new mongoose.Schema({
        products: [ProductSchema],
       })

        // Map <productId, product> this is what I want to achieve

CodePudding user response:

   const ProductsSchema = new mongoose.Schema({
     products: {
       type: Map,
       of:ProductSchema        
   })
  • Related