Search code examples
node.jsmongodbexpressdatabase-schemamongoose-schema

Mongoose is not creating collection name from variable


schema.js

****************************************************************
var nameOfCategory = "hello";
ecomm.createProductCollection = async (categoryName) =>{
  nameOfCategory = categoryName;
}

const productSchema = new mongoose.Schema({
  productName:{
    type: String,
    require: true
  }
},
// { collection: nameOfCategory }
)
ecomm.productModel = new mongoose.model(nameOfCategory, productSchema, nameOfCategory)

*******************************************************************************************
controller.js

await ecomm.createProductCollection("someDynamicName")
await ecomm.productModel.create(product);

-----------------------------------------------------------------------

Expected Result: Collection created with name "someDynamicName". Actual Result: Collection created with name "hello".

But while printing in console, nameOfCategory displays "someDynamicName"


Solution

  • This works out when the productSchema is created inside function. But still could not find the reason why the code in question is not working.

    schema.js
    
    ****************************************************************
    
    ecomm.createProductCollection = async (categoryName) =>{
      nameOfCategory = categoryName;
    const productSchema = new mongoose.Schema({
      productName:{
        type: String,
        require: true
      }
    },
    // { collection: nameOfCategory }
    )
    ecomm.productModel = new mongoose.model(nameOfCategory, productSchema, nameOfCategory)
    }