Gearbox Interacting with the Databse - Decatur-Robotics/Common-Library-And-Wiki GitHub Wiki

Accessing the Database for dummies.

Gearbox uses MongoDb as our database, this guide is going to assume that you have a mongo instance up and running, but if you dont its easy to either run it locally or spin up a cloud based "Atlas" instance, then place MONGODB_URI=[Replace this with your uri] and DB=demo in your .env file.

Ok, now that you have a database, how do you interact with it?

Pt 1. The Basics

Because, unlike localstorage or variables, the database is not stored locally on the client, we have to make an API request to access it. You can see this in action by navigating to the profile.tsx file (it can be found at the bottom of the pages folder). On the line 9 you will see the code const api = new ClientAPI([API KEY]); this allows us to make API calls by using the syntax await api.[whatever api call you want to make].

Next, navigate to line 66, whats important here is the word async. By putting the word async before a function that function becomes capable of making API calls. Finally, look down to line 68 which reads const team = await api.findTeamByNumber(num);. This line of code sets the variable team to the team object associated with the provided number. The line api.findTeamByNumber(num); makes an API call to the database requesting the team object associated with the number provided, then returns the databases response (in this case, that response is a team object). If the number we provided the API call with was "4026", than the database would have responded with the decatur robotics team object, and team would have been set to it. We could then access properties of team, such as team.name in order to display the name of the team, in this case, Decatur Robotics.

We can also make changes to the database using the API. Navigate to line 149 and see the line api.changePFP(session?.user?._id,newPicUrl). This api call allows us to change a users profile picture. We change the profile picture by providing the id of the user we want to change (session?.user?._id) and the URL of the image that we want to change to (newPicUrl). The API then takes the values we passed it and use them to tell the database to change the profile picture property of the user associated with the userId we provided to the URL we provided.

This example shows the fundamentals of how we interact with the database, we create declare our api at the top, then create a async function, and place api.[whatever call you want to make] in order to access the database.

Pt. 2 Looking behind the hood.

Now you should understand roughly how to make an API call and interact with the database, but how do you know what API calls even exist? And what's actually happening when you make one. This section aims to explain at least the first of those questions, and give you a basic understanding of the second.

First things first, navigate to the API.ts file (within the lib) folder, and the ClientAPI.ts folder (within the client folder, which itself is in the lib folder.). Lets look at the ClientAPI.ts folder first. On line 9 you can observe the line export default class ClientAPI this ClientAPIclass is what we referenced when we declared our api object in part 1. Skipping down a little bit, to any part of the file below line 39, we can see a large number of async functions. These functions are all formatted like async [functionName](parameters):<return type>(return type only exists if the function has a return) {return await this.request("/name", {parameters})}. We'll lock at API.ts in a moment, but first I want to explain what these functions do. Each function calls a certain API from the API.ts file, and passes it the parameters it needs to function. The "/name" part of the function specifies which function is being called. Navigate to line 102 of ClientAPI.ts then switch over to API.ts and navigate to line 376.

On API.ts within the changePFP function, notice the line db.updateObjectById, this accesses the database db and calls one of its built in functions updateObjectById in order to update an object. Notice <User> after the function call, this tells us that the object being updated is a User object. After that, within parenthesis, notice Collections.Users, this tells the function that the change its making will occur within the Users collection. The function then says new ObjectId(data.userid) this creates a new objectId object (what the database needs to identify an object) using the userId we provided in ClientAPI.ts. In this part of the API call all paremeters passed to API.ts are accessed by calling data.[parameter]. After providing the id of the user object we want to change, we then face the code {image:{`${data.newImage}`}) the image: section of the code tells the database that the property being modified is the image property, then ${data.newImage} specifies what the property should be set to (the reason for the ${} is that image property requires a string, and by using backticks to to mark our text, we can place the value of an object or variable in that text by using ${}).

This syntax can be used to change any data in the database just by changing a few parts of the updateObjectById. I would recommend looking at a few other functions in this file to get a feeling for how functions are written. I would also recommend looking at API calls that return a value to get a understanding of how they work (hint: they're pretty similar to calls that update a value.)

Pt. 3 The easy part

Now that you understand how API calls are written, this is the easy part. In order to create your own API call, you can simply copy the syntax for the other API calls, but swap out a few parameters. For example, try writing an API call that updates a users name!

⚠️ **GitHub.com Fallback** ⚠️