1
00:00:00,420 --> 00:00:01,620
In this video.

2
00:00:01,620 --> 00:00:06,210
Let's go ahead and create a function to connect to MongoDB.

3
00:00:06,240 --> 00:00:13,740
So inside the config, let's create one file called DB Connect dot JS.

4
00:00:14,980 --> 00:00:24,190
So let's import the mongoose package and it's equal to required and mongoose.

5
00:00:24,310 --> 00:00:27,760
So I'm going to be as Kong's DB connect.

6
00:00:27,910 --> 00:00:32,229
So inside the function body I'm going to make use of try and catch.

7
00:00:32,350 --> 00:00:39,670
And inside a try, I'm going to connect by making use of a and then mongoose dart connect.

8
00:00:40,620 --> 00:00:48,060
And this function requires only one argument, and that is the connection string for MongoDB.

9
00:00:48,090 --> 00:00:53,220
For the meantime, let's add some placeholder and call it as mongo.

10
00:00:53,250 --> 00:00:59,100
You are ill and I'm going to show you how we're going to get the MongoDB.

11
00:00:59,100 --> 00:01:00,150
You are error.

12
00:01:00,420 --> 00:01:08,610
So in case everything goes right inside here, we are going to console.log by saying that DB connected.

13
00:01:09,590 --> 00:01:15,590
And in case something goes wrong, we are going to console.log this by saying that.

14
00:01:16,190 --> 00:01:22,970
And I want to add the exact error and we have access on the error message.

15
00:01:26,470 --> 00:01:27,040
All right.

16
00:01:27,040 --> 00:01:31,390
The last step is that I need to export this function.

17
00:01:31,390 --> 00:01:39,490
So I'm going to be as module dot exports and is equal to DV connect.

18
00:01:39,910 --> 00:01:44,020
But this how I would like to export this function.

19
00:01:44,140 --> 00:01:50,350
And so this way I'm going to call the function automatically as DB connect.

20
00:01:50,500 --> 00:01:56,740
So anywhere I require the file, this function is going to run automatically.

21
00:01:56,740 --> 00:01:58,690
So let me remove this one.

22
00:01:59,020 --> 00:02:00,940
So let's get back to the server.

23
00:02:00,940 --> 00:02:07,270
That's where I want to call the DB connection and going to be as required.

24
00:02:08,370 --> 00:02:13,730
And force last config and then DB connect and that is it.

25
00:02:13,740 --> 00:02:22,260
So if I check the terminal and here you can see that we have beautiful error by saying that invalid

26
00:02:22,260 --> 00:02:28,300
scheme meaning that we didn't provide the valid MongoDB you are error.

27
00:02:28,320 --> 00:02:33,630
So the next video, let's see how we are going to create MongoDB connection in string.

