1

I want to add dynamic fields to Mongoose Schema every time before add/update record. Since, I have defined the fields into the separate JSON file and want the same JSON fields to be added dynamically every time to the Mongoose schema. Is this possible and how to do that?

Example Simple Modal:

const blogSchema = new Schema({
  title:  String, // String is shorthand for {type: String}
  body:   String,
});  

let dynamicfields=[
  author: String,
  comments: [{ body: String, date: Date }],
  date: { type: Date, default: Date.now },
  hidden: Boolean,
]

How can I add dynamicFields to schema every time?

Sourav
  • 3,025
  • 2
  • 13
  • 29
Satnam 363
  • 19
  • 1

1 Answers1

0

You can simply make your schema-free using strict or you can use Mixed.

It won't let your dynamic values save to your DB.

const blogSchema = new Schema({ 
title: String, // String is shorthand for {type: String} 
body: String 
},
{
  strict: false
});

Using Mixed:

let schema = new Schema({ 
title: String, // String is shorthand for {type: String} 
body: String 
metaData: Schema.Types.Mixed 
})

Here you can save dynamic values to metaData.

Apoorva Chikara
  • 8,277
  • 3
  • 20
  • 35