Since MongoDB and SQL databases differ so much, choosing the right tool for a given job is crucial.
Since NoSQL databases put fewer restrictions on the data, it might be a good choice for an application evolving quickly.
We still might need to update our data as our schema changes.
For example, we might want to add a new property containing the user’s avatar URL.
When it happens, we still should deal with documents not containing our new property.
We can do that by writing a script that puts a default value for old documents.
Alternatively, we can assume that this field can be missing and handle it differently on the application level.
On the contrary, adding a new property to an existing SQL database requires writing a migration that explicitly handles the new property.
This might seem like a bit of a chore in a lot of cases.
However, with MongoDB, it is not required.
This might make the work easier and faster, but we need to watch out and not lose the integrity of our data.
If you want to know more about SQL migrations, check out The basics of migrations using TypeORM and Postgres
SQL databases such as Postgres keep the data in tables consisting of columns and rows.
A big part of the design process is defining relationships between the above tables.
For example, a user can be an author of an article.
On the other hand, MongoDB is a non-relational database.
Therefore, while we can mimic SQL-style relationships with MongoDB, they will not be as efficient and foolproof.
In the previous parts of this series, we’ve used TypeORM to connect to our PostgreSQL database and manage our data.
For MongoDB, the most popular library is Mongoose.
With MongoDB, we operate on documents grouped into collections.
To start saving and retrieving data with MongoDB and Mongoose, we first need to define a schema.
This might seem surprising at first because MongoDB is considered schemaless.
Even though MongoDB is flexible, Mongoose uses schemas to operate on collections and define their shape.
Above, a few important things are happening.
Thanks to using the new: true parameter, the findByIdAndUpdate method returns an updated version of our entity.
By using overwrite: true, we indicate that we want to replace a whole document instead of performing a partial update.
This is what differentiates the PUT and PATCH HTTP methods.
If you want to know more, check out TypeScript Express tutorial #15.
Using PUT vs PATCH in MongoDB with Mongoose.
In this article, we’ve learned the very basics of how to use MongoDB with NestJS.
To do that, we’ve created a local MongoDB database using Docker Compose and connected it with NestJS and Mongoose.
To better grasp MongoDB, we’ve also compared it to SQL databases such as Postgres.
There are still a lot of things to cover when it comes to MongoDB, so stay tuned!