Create a backend server side for React Native App using NestJS connected to MongoDB Atlas

Rihem Larbi
5 min readJan 11, 2024

--

In this document we will create a backend server to connect to MongoDB Atlas, as a good practice it’s better to separate backend from frontend to enhance: scalability, flexibility, separation concerns, and facilitates independent Continuous Integration (CI) and Continuous Deployment (CD).

1- Create backend server using Nest.js

First of all you should install Nest CLI using this command.


npm install -g @nestjs/cli

once completed, confirm that the Nest CLI has been installed successfully by running this command.

nest --version

you will see an output indicating the last version installed on your machine.

10.2.1 _ 

now you can create a backend project using the nest command.

nest new backend-project

After that, you should choose a package manager you would like to use. you can select npm and hit enter to install Nests.js project. you will get a folder with these contents.

Now, we could integrate MongoDB by using mongoose. you should move into the created directory and run this command.

cd backend-project
npm install --save @nestjs/mongoose mongoose

then, you can open your project in visual studio code using this command.

code .

In main.ts file you can edit the default port, by default the port is 3000 but to avoid port conflict with the react native application you can change it to 5000 as shown bellow.

with that done you can start the application using the following command.

npm run start:dev

this will run the application on port 5000, you can navigate to http://localhost:5000/ from your browser and you will see you application running.

2- Connect MongoDB Atlas to backend server

to connect to MongoDB you should go to app.module.ts and add this code in the import section.

import { MongooseModule } from '@nestjs/mongoose'; 

then you should add the root to the mongoDB in @Module in imports section of app.module.ts

    MongooseModule.forRoot('mongodb+srv://<username>:<password>@cluster0.yea28ie.mongodb.net/?retryWrites=true&w=majority'),

you can find the root to the mongoDB by clicking to connect.

Then click Drivers.

after that copy the link and put it in the imports section of app.module.ts

3- Add data to MongoDB Atlas

First of all you should create a schema and a model of your data, to do that you can create a file test.model.ts inside your folder named test.

Next you can create your schema and the module in the same file but you should import mongoose.

import * as mongoose from 'mongoose';

Then you can for example create a schema similar to the example bellow (PS: id property will not be added in the schema because it is autogenerated).

export const TestSchema = new mongoose.Schema({
property_1: { type: String, required: true },
property_2: { type: String, required: true },
property_3: {
property_3_1: {
type: String,
required: true
},
property_3_2: {
type: String,
required: true
}
},
});

then, you can create the model of the schema as shown in the example below (PS: the id should be added in this case).

export interface Test{
id: String;
property_1: String;
property_2: String;
property_3: Object;
}

now, we should create the service for our schema to do that we should create a file in the same folder (Test in our case) and named test.service.ts in this file we should add this code

import { Injectable } from '@nestjs/common';
import { InjectModel } from '@nestjs/mongoose';
import { Model } from 'mongoose';
import { Test} from './test.model'
@Injectable()
export class TestService {

constructor(
@InjectModel('Test')
private readonly testModel: Model<Test>,
) {}
async insertTest( property_1: String,
property_2: String,
property_3: Object){
const newTest= new this.testpModel({property_1,property_2,property_3})
const result= await newTest.save() ;
return result.id as string
}
}

Then, we should create the controller file, you can name your file test.controller.ts, this file will contain all the actions (POST, GET,PUT), in the code bellow we just tested the POST action to validate the connection with the MongoDB Atlas database.

import { Controller, Post,Body, Get } from '@nestjs/common';
import{TestService} from './test.service';

@Controller('test')
export class TestController {
constructor(private readonly testService: TestService) {}


@Post()
async addTest(
@Body('property_1') property1: string,
@Body('property_2') property2: string,
@Body('propert_3') property3: object,
) {
const generatedId = await this.testService.insertTest(
property1,
property2,
property3,
);
return { id: generatedId };
}

}

In the same folder test, we should now create our module file, you can create a file named test.module.ts in this file we will import our schema, controller and services as shown bellow.

import { Module } from '@nestjs/common';
import {MongooseModule} from '@nestjs/mongoose'
import { TestController } from './test.controller';
import { TestService } from './test.service';
import { TestSchema } from './test.model';
@Module({
imports:[MongooseModule.forFeature([{ name: 'Test', schema: TestSchema }])],
controllers: [TestController],
providers: [TestService],
})
export class TestModule {}

Alos, in app.module.ts we should add the TestModule so the app.module.ts will look like bellow.

import { Module } from '@nestjs/common';
import { AppController } from './app.controller';
import { AppService } from './app.service';
import { MongooseModule } from '@nestjs/mongoose';
import { TestModule } from './test/Test.module';
@Module({
imports: [
TestModule,
MongooseModule.forRoot('mongodb+srv://<username>:<password>@cluster0.yea28ie.mongodb.net/?retryWrites=true&w=majority'),
],
controllers: [AppController],
providers: [AppService],
})
export class AppModule {}

To summarize, the directory should be like bellow.

>src
->test
test.model.ts
test.controller.ts
test.module.ts
test.service.ts
app.controller.ts
app.module.ts
app.service.ts
main.ts

After that, you should run the application by using the following command.

npm run start:dev

Finally, we can test our code by using Postman to post data in the MongoDB Atlas database as shown bellow.

we have successfully added data to our MongoDB Atlas database, you can check the MongoDB by clicking Browse Collection and you can verify that the data has been added successfully.

I hope that this document was helpful.

Thank you for your patient.

--

--