William Hu
William Hu

Reputation: 16151

Mongoose Change Schema Field Type

How to change the type of one field in Mongoose?

For example:

var FooSchema = new Schema({
  fooDate: {
    type: String,
    unique: true,
    required: true,
    trim: true
  }
}

fooDate is a string type, I want to change it to Date type?

If I just change it, what will happen to the existing data? What's the proper way to migrate the old data?

Thanks.

Upvotes: 1

Views: 3733

Answers (2)

Wasiq Muhammad
Wasiq Muhammad

Reputation: 3118

You can change the data type any time .e.g

var FooSchema = new Schema({
  fooDate: {
    type: Date,
    unique: true,
    required: true,
    trim: true
  }
}

Now the new document records will be enter according to new data type. for existing or previous one it depends how you store a string you should make a script either in python or nodejs it depends upon you. first fetching the all records and make a helper function that take string and convert the string into data of that time you could easily do in javascript using Date Object as Date('2014-08-12')

Then you update all the previous records that you fetched in this way you can do consistency

Upvotes: 1

Akrion
Akrion

Reputation: 18515

Well it would depend on how do you have your date stored as string. Is it a valid date? Lets assume that it is either in valid ISO format or something like this:

"2019-03-20"  or "2019-03-20T09:15:37.220Z"

If you simply change from String to Date mongoose would convert that for you and would treat that as the new type. So you would not need to migrate per se your date. When you get a model its fooDate would now be Date vs String before.

However the main issue you are facing now is querying data that is in two formats. Because any new records now would be saved as dates vs strings.

So you would be able to get by with the type change but while that would buy you some time you would need to migrate your data to reduce the friction during querying later. Migrating a single field would be a trivial migration script so there is nothing scary there.

PS. You can always test this btw. I just did with a simple schema and a saved record which had date as String then I updated the schema and did a simple Model.find to get that record and validate that now the date is an actual date and there was no issue with the model from mongoose. As long as the date string was in the correct date format.

Upvotes: 2

Related Questions