So far, in this series, we’ve focused on working with SQL and the Postgres database. While PostgreSQL is an excellent choice, it is worth checking out the alternatives. In this article, we learn about how MongoDB works and how it differs from SQL databases. We also create a simple application with MongoDB and NestJS.
You can find the source code from the below article in this repository.
MongoDB vs. SQL Databases
The design principles of MongoDB differ quite a bit from traditional SQL databases. Instead of representing data with tables and rows, MongoDB stores it as JSON-like documents. Therefore, it is relatively easy to grasp for developers familiar with JavaScript.
Documents in MongoDB consist of key and value pairs. The significant aspect of them is that the keys can differ across documents in a given collection. This is a big difference between MongoDB and SQL databases. It makes MongoDB a lot more flexible and less structured. Therefore, it can be perceived either as an advantage or a drawback.
Advantages and drawbacks of MongoDB
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.
Using MongoDB with NestJS
So far, in this series, we’ve used Docker to set up the architecture for our project. We can easily achieve that with MongoDB also.
1version: "3"
2services:
3 mongo:
4 image: mongo:latest
5 environment:
6 MONGO_INITDB_ROOT_USERNAME: ${MONGO_USERNAME}
7 MONGO_INITDB_ROOT_PASSWORD: ${MONGO_PASSWORD}
8 MONGO_INITDB_DATABASE: ${MONGO_DATABASE}
9 ports:
10 - '27017:27017'Above, you can see that we refer to a few variables. Let’s put them into our .env file:
1MONGO_USERNAME=admin
2MONGO_PASSWORD=admin
3MONGO_DATABASE=nestjs
4MONGO_HOST=localhost:27017In 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.
1npm install --save @nestjs/mongoose mongooseLet’s use Mongoose to connect to our database. To do that, we need to define a URI connection string:
1import { Module } from '@nestjs/common';
2import { MongooseModule } from '@nestjs/mongoose';
3import { ConfigModule, ConfigService } from '@nestjs/config';
4import PostsModule from './posts/posts.module';
5import * as Joi from '@hapi/joi';
6
7@Module({
8 imports: [
9 ConfigModule.forRoot({
10 validationSchema: Joi.object({
11 MONGO_USERNAME: Joi.string().required(),
12 MONGO_PASSWORD: Joi.string().required(),
13 MONGO_DATABASE: Joi.string().required(),
14 MONGO_PATH: Joi.string().required(),
15 }),
16 }),
17 MongooseModule.forRootAsync({
18 imports: [ConfigModule],
19 useFactory: async (configService: ConfigService) => {
20 const username = configService.get('MONGO_USERNAME');
21 const password = configService.get('MONGO_PASSWORD');
22 const database = configService.get('MONGO_DATABASE');
23 const host = configService.get('MONGO_HOST');
24
25 return {
26 uri: `mongodb://${username}:${password}@${host}`,
27 dbName: database,
28 };
29 },
30 inject: [ConfigService],
31 }),
32 PostsModule,
33 ],
34 controllers: [],
35 providers: [],
36})
37export class AppModule {}Saving and retrieving data
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.
Defining a schema
Every schema maps to a single MongoDB collection. It also defines the shape of the documents within it.
1import { Prop, Schema, SchemaFactory } from '@nestjs/mongoose';
2import { Document } from 'mongoose';
3
4export type PostDocument = Post & Document;
5
6@Schema()
7export class Post {
8 @Prop()
9 title: string;
10
11 @Prop()
12 content: string;
13}
14
15export const PostSchema = SchemaFactory.createForClass(Post);With the @Schema() decorator, we can mark our class as a schema definition and map it to a MongoDB collection. We use the @Prop() decorator to definite a property of our document. Thanks to TypeScript metadata, the schema types for our properties are automatically inferred.
We will expand on the topic of defining a schema in the upcoming articles.
Working with a model
Mongoose wraps our schemas into models. We can use them to create and read documents. For our service to use the model, we need to add it to our module.
1import { Module } from '@nestjs/common';
2import { MongooseModule } from '@nestjs/mongoose';
3import PostsController from './posts.controller';
4import PostsService from './posts.service';
5import { Post, PostSchema } from './post.schema';
6
7@Module({
8 imports: [
9 MongooseModule.forFeature([{ name: Post.name, schema: PostSchema }]),
10 ],
11 controllers: [PostsController],
12 providers: [PostsService],
13})
14class PostsModule {}
15
16export default PostsModule;We also need to inject the model into our service:
1import { Model } from 'mongoose';
2import { Injectable } from '@nestjs/common';
3import { InjectModel } from '@nestjs/mongoose';
4import { Post, PostDocument } from './post.schema';
5
6@Injectable()
7class PostsService {
8 constructor(@InjectModel(Post.name) private postModel: Model<PostDocument>) {}
9}
10
11export default PostsService;Once we do that, we can start interacting with our collection.
Fetching all entities
The most basic thing we can do is to fetch the list of all of the documents. To do that, we need the find() method:
1import { Model } from 'mongoose';
2import { Injectable } from '@nestjs/common';
3import { InjectModel } from '@nestjs/mongoose';
4import { Post, PostDocument } from './post.schema';
5
6@Injectable()
7class PostsService {
8 constructor(@InjectModel(Post.name) private postModel: Model<PostDocument>) {}
9
10 async findAll() {
11 return this.postModel.find();
12 }
13}Fetching a single entity
Every document we create is assigned with a string id. If we want to fetch a single document, we can use the findById method:
1import { Model } from 'mongoose';
2import { Injectable } from '@nestjs/common';
3import { InjectModel } from '@nestjs/mongoose';
4import { Post, PostDocument } from './post.schema';
5import { NotFoundException } from '@nestjs/common';
6
7@Injectable()
8class PostsService {
9 constructor(@InjectModel(Post.name) private postModel: Model<PostDocument>) {}
10
11 async findOne(id: string) {
12 const post = await this.postModel.findById(id);
13 if (!post) {
14 throw new NotFoundException();
15 }
16 return post;
17 }
18
19 // ...
20}Creating entities
In the fourth part of this series, we’ve tackled data validation. Let’s create a Data Transfer Object for our entity.
1import { IsString, IsNotEmpty } from 'class-validator';
2
3export class PostDto {
4 @IsString()
5 @IsNotEmpty()
6 title: string;
7
8 @IsString()
9 @IsNotEmpty()
10 content: string;
11}
12
13export default PostDto;We can now use it when creating a new instance of our model and saving it.
1import { Model } from 'mongoose';
2import { Injectable } from '@nestjs/common';
3import { InjectModel } from '@nestjs/mongoose';
4import { Post, PostDocument } from './post.schema';
5import PostDto from './dto/post.dto';
6
7@Injectable()
8class PostsService {
9 constructor(@InjectModel(Post.name) private postModel: Model<PostDocument>) {}
10
11 create(postData: PostDto) {
12 const createdPost = new this.postModel(postData);
13 return createdPost.save();
14 }
15
16 // ...
17}Updating entities
We might also need to update an entity we’ve already created. To do that, we can use the findByIdAndUpdate method:
1import { Model } from 'mongoose';
2import { Injectable } from '@nestjs/common';
3import { InjectModel } from '@nestjs/mongoose';
4import { Post, PostDocument } from './post.schema';
5import { NotFoundException } from '@nestjs/common';
6import PostDto from './dto/post.dto';
7
8@Injectable()
9class PostsService {
10 constructor(@InjectModel(Post.name) private postModel: Model<PostDocument>) {}
11
12 async update(id: string, postData: PostDto) {
13 const post = await this.postModel
14 .findByIdAndUpdate(id, postData)
15 .setOptions({ overwrite: true, new: true });
16 if (!post) {
17 throw new NotFoundException();
18 }
19 return post;
20 }
21
22 // ...
23}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.
Deleting entities
To delete an existing entity, we need to use the findByIdAndDelete method:
1import { Model } from 'mongoose';
2import { Injectable } from '@nestjs/common';
3import { InjectModel } from '@nestjs/mongoose';
4import { Post, PostDocument } from './post.schema';
5import { NotFoundException } from '@nestjs/common';
6
7@Injectable()
8class PostsService {
9 constructor(@InjectModel(Post.name) private postModel: Model<PostDocument>) {}
10
11 async delete(postId: string) {
12 const result = await this.postModel.findByIdAndDelete(postId);
13 if (!result) {
14 throw new NotFoundException();
15 }
16 }
17
18 // ...
19}Defining a controller
Once we’ve got our service up and running, we can use it with our controller:
1import {
2 Body,
3 Controller,
4 Delete,
5 Get,
6 Param,
7 Post,
8 Put,
9} from '@nestjs/common';
10import PostsService from './posts.service';
11import ParamsWithId from '../utils/paramsWithId';
12import PostDto from './dto/post.dto';
13
14@Controller('posts')
15export default class PostsController {
16 constructor(private readonly postsService: PostsService) {}
17
18 @Get()
19 async getAllPosts() {
20 return this.postsService.findAll();
21 }
22
23 @Get(':id')
24 async getPost(@Param() { id }: ParamsWithId) {
25 return this.postsService.findOne(id);
26 }
27
28 @Post()
29 async createPost(@Body() post: PostDto) {
30 return this.postsService.create(post);
31 }
32
33 @Delete(':id')
34 async deletePost(@Param() { id }: ParamsWithId) {
35 return this.postsService.delete(id);
36 }
37
38 @Put(':id')
39 async updatePost(@Param() { id }: ParamsWithId, @Body() post: PostDto) {
40 return this.postsService.update(id, post);
41 }
42}The crucial part above is that we’ve defined the ParamsWithId class. With it, we can validate if the provided string is a valid MongoDB id:
1import { IsMongoId } from 'class-validator';
2
3class ParamsWithId {
4 @IsMongoId()
5 id: string;
6}
7
8export default ParamsWithId;Summary
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!