Muhammad Ali
Muhammad Ali

Reputation: 369

creating new model field in mongoose

so lately I have had a model customer.js which had following fields:

   const customer = new schema({
    name:String,
    email:String,
    age:Number,
    });

now after few months I have added new field their description. My question is if I move this new model to the production. How will it effect my previous model and the customers who were created using old model? I am afraid if I move this new to production it will throw error description undefined in the UI console becuase old customers had no such field description?

Upvotes: 0

Views: 69

Answers (1)

tom
tom

Reputation: 740

To avoid breaking things:

  1. Update your schema with the new description field:
const customer = new schema({
  name: String,
  email: String,
  age: Number,
  description: String,
});
  1. Run a db.collection.update(...) to ensure you don't break things and every customer has the same schema:
db.customers.updateMany(
  { description: { $exists: false } } // All the customers without a description
  { $set: { description: '' } } // Set the description field to an empty string
)

Upvotes: 2

Related Questions