1

I have created a MongoDB collection with mongoose model using express (node.js) and it is working well. And now I want to restructure the model of the same collection. For that I have to delete the collection in the database and restart the server so that it is updating with new model. But I have live data which is in use. So how can I restructure the collection without deleting it.

Do we have any other way to resolve this issue which is not to delete the collection and restart the server to update the mongoose model in the collection?

My old Model looks like this:

new mongoose.Schema({
name: {type:String},
age: {type: String, required: true}
});

And I want this new model to be updated in the same collection:

new mongoose.Schema({
name: {type:String, unique: true},
age: {type: Number, required: true},
grade: {type:Number}
});
  • Maybe it will not delete your existing documents, backup your collection, restructure your model, restart the server, and see what happens – SuleymanSah Nov 27 '19 at 16:13
  • @SuleymanSah, thank you for your response. If we don't delete the collection but restart the server updated model, the model is not reflecting in the collection. So I tried deleting the collection and restart the server it got effected but data is getting deleted. – ramprakash seepana Nov 27 '19 at 16:17
  • I just tried this scenario, and the change in the model is reflected into the collection. Are you sure you are adding the new grade field to your request body while posting? – SuleymanSah Nov 27 '19 at 16:21
  • If we have the age as type String in old model and updated as type Number in new model, are you sure it will get reflected? Actually it is not reflecting in the collection. – ramprakash seepana Nov 27 '19 at 16:25
  • That was not the question. I am talking about newly added grade field. – SuleymanSah Nov 27 '19 at 16:27
  • :) got you. I will change that one as well in my question. But as a matter of fact the new field is also not reflecting in the collection. – ramprakash seepana Nov 27 '19 at 16:29

1 Answers1

0

You can make a cron that runs through the existing collection and updates the old documents with your new field.

Zamfi
  • 327
  • 2
  • 9