TypeScript Mongoose handle Schema and DB conflict

Viewed 15

I am quite new to MongoDB and mongoose and I'm not sure how to resolve conflicts with the schema and the database. By this I mean if I have an already established database and then I decide to expand on the schema in my project, adding defaults, how do I efficiently make those changes in the database as well?

1 Answers

Expanding a Mongoose schema typically doesn't require any explicit synchronisation with the database, because MongoDB itself is schemaless and doesn't really care about what you store in it.

Things like defaults are handled by Mongoose itself, not by MongoDB, so adding defaults to your schema will work just fine. However, because they are handled by Mongoose, this means that any data already stored in the database will not be updated if you set a default. This also applies to changing the type of a field: if a field was previously a Number, and you change it to a String, existing database documents will not get changed. But this usually doesn't present an issue.

The only common change that I can think of that may require manual intervention is when your schema previously have fields marked as unique, and you remove the uniqueness constraint from your schema. In such a case, you need to manually remove the unique index that was previously created by Mongoose (it will not remove it by itself).

Related