How to add new property to mongoDb model? How to add new property to mongoDb model? mongoose mongoose

How to add new property to mongoDb model?


As Sharrzard Gh said, MongoDB doesn't allow you to add a new property to your model after it's been defined. Instead, use a structure like this, to define an initially empty property that you will use later to store the trend data.

const CoinSchema = new Schema({  specName: { type: String, required: true },  fullName: { type: String, required: true },  category:{ type: String, required: true },  coinName: { type: String, required: true },  trend: { type: String, required: true, default: '' }  // <- Add this property});module.exports = mongoose.model("coins", CoinSchema);

You can change the trend data type to an array or object if you need to store more complex data or a series of data points for historical trend tracking, if you want.

Try something like this:

trend: { type: Object, required: true, default: {} }

or

trend: { type: [String] , required: true, default: [] }


I was able to add new properties in the model even after the creation of the model in Node.js using:

insertMany(table_data, { strict: false });

where table_data container the old data appended with the new properties. The strict: false did the magic.

Order Model in Node:

const mongoose = require ('mongoose');const OrdersSchema = new mongoose.Schema({  sr_no :{type: Number, required:true},  customer_name :{type: String, required:true},  product_name: String,  codes: String,  code_date:{    type:Date,    default: Date.now()  },  design : String,  design_date :{    type:Date,    default: Date.now()  },  design_approval :{    type:String,    default: ''  },  design_approval_date :{    type:Date,    default: Date.now()  },  send_to_printer :{    type:String,    default: ''  },  send_to_printer_date :{    type:Date,    default: Date.now()  },  proof_approval :{    type:String,    default: ''  },  proof_approval_date :{    type:Date,    default: Date.now()  },  shipping : String,  ship_date :{    type:Date,    default: Date.now()  },  received :{    type:String,    default: ''  },  received_date :{    type:Date,    default: Date.now()  },  completed : String,  notes : String,  printing :{    type:String,    default: ''  },  printing_date :{    type:Date,    default: Date.now()  },  stapling :{    type:String,    default: ''  },  stapling_date :{    type:Date,    default: Date.now()  },  user_id :{type: Number, required:true}},{strict: false});OrdersSchema.index({ sr_no: -1 });const Orders = mongoose.model(  'Orders',  OrdersSchema);module.exports = Orders;

In Mongo Compass the first record appeared like:enter image description here

And another record in the same collection was:

enter image description here