How do front-end developers build databases

I was recently asked what is the easiest way for a front-end developer to store user data. Now just for this part, let me show you how to do it.

Set up a database

First, actually have a database. You can find a free one on the MLab website. Once registered, click Create New in the MongoDB Deployment (Deployments) column. The sandbox database that was created was free, so I’m going to use that.

Once the database is created, create an account so you can verify your identity. Click the name of the database, then users, then Add Database User. Write down the username and password you choose and use it later.

At the top of the database page, you should see the MongoDB address. This is the database page address, just like a web page address. By convention, the MongoDB address format is as follows:

Mongodb ://< username >:< password >@< host >:< port >/< database name >Copy the code

For example, my database is:

mongodb://admin:[email protected]:11885/medium
Copy the code

Setting up the server

We will use Node platform for server background. To skip the build process, you can clone my project on Glitch by clicking here

Take a look at the server.js startup file I wrote:

// Initialize the project const express = require('express'); Const app = express(); App. use(require('body-parser').json()) // Automatically parse request data, Get ("/", function (request, response) {response.send("TODO") // All requests are responded with a string "TODO"}); App.post ("/", function (request, response) {response.send("TODO") // All requests are responded with a string "TODO"}); App.put ("/", function (request, response) {response.send("TODO") // All requests are answered with a string "TODO"}); // Since we are using glitch's network domain, the PORT for listening requests should be set to process.env.port. // Otherwise, the port can be set to 80 or something. var listener = app.listen(process.env.PORT, function () { console.log('Your app is listening on port ' + listener.address().port); });Copy the code

Enter the Express library, which handles requests sent to the server.

A cross-domain request is a request sent from a web site in one domain to a server in another domain. Use (require(CORS)) is used to allow the request. App.use (require(‘body-parser’).json()) automatically parses the request and converts it to JSON.

We then enter a processing path and a callback for the get method. That is, whenever a site’s/path page is opened, the request is handled by that callback function. The basic domain name is implicit, so in the case of shiny-koala.glitch.com, path /about refers to the http://shiny-koala.glitch.com/about address.

More precisely, “opening the page” means sending a request to the server using the GET method. The different Http methods are really just different types of requests sent to the server. We only use the following methods:

  • GETThe getResource () method is used to get resources from the server. For example, opening a Facebook page loads the necessary HTML, CSS, and JavaScript resources.
  • POSTMethod is used to create resources on the server. For example, if you post on Facebook, the message in the post is throughPOSTRequests are sent to Facebook servers.
  • PUTThe update resource () method is used to update resources on the server. For example, when you edit a post, the edited content passesPUTThe request is sent to Facebook servers.

The app.post and app.put functions work exactly the same as the app.get functions. Of course, these two functions do not handle GET methods, but POST and PUT methods, which makes perfect sense.

The path

When developing a server, you need to do some testing. You can run HTTP requests using this website REST Test test, which is very convenient. Or you can use Insomnia.

To see the Glitch program’s address, click the Show button.

So far, we’ve only used the/path. But we want to store information for different users, so we need to set up a different path for each user. For example: /ZaninAndrea and /JohnGreen paths.

This creates a problem: it is impossible to write all paths individually, and this approach scales poorly. We need route parameters so that we can write a path: /:user.

The colon tells the Express library to catch any path that starts with a/and then consists of only alphanumeric characters.

Here are some examples:

  • /ZaninAndreaTo capture
  • /Johnny45To capture
  • /alex/score Don’tcapture

The value of user can then be obtained in the request.params.user variable.

App.get ("/:user", function (request, response) {response.send(request.params.user)}); // Basic path app.post("/:user", function (request, response) {response.send(request.params.user)}); // Basic path app.post("/:user", function (request, response) {response.send(request. App.put ("/:user", function (request, response) {response.send(request.params.user)});Copy the code

The server can now respond to all queries with user names.

Add data to the database

Now that we know who the user is, we’re going to store the user information.

To query the database, we’ll use the mongodb library. You can install it in one of two ways:

npm install mongodb --save
Copy the code

If you’re using Glitch, you can also go to the package.json file and click the Add Package button.

Let’s load the library and store the MongoDB address in a variable:

const mongodb = require('mongodb'); // add mongodb library const uri = process.env.uri;Copy the code

This address is sensitive information because it is enough to access the database. It is best to put this address in a. Env file so that others can’t see it.

URI=mongodb://admin:[email protected]:11885/medium
Copy the code

Glitch automatically loads this variable into the process.env variable from the. Env file.

Connecting to the database is an asynchronous operation, so we’ll wrap the server setup step in a callback function, like this:

Mongo. MongoClient. Connect (uri, function (err, db) {/ / basic path app. Get ("/" user ", function (request, response) { response.send(request.params.user) }); // Basic path app.post("/:user", function (request, response) {response.send(request.params.user)}); // Basic path app.post("/:user", function (request, response) {response.send(request. App.put ("/:user", function (request, response) {response.send(request.params.user)}); // Since we are using glitch's network domain, the PORT for listening requests should be set to process.env.port. // Otherwise, the port can be set to 80 or something. var listener = app.listen(process.env.PORT, function () { console.log('Your app is listening on port ' + listener.address().port); }); })Copy the code

Databases are organized as collections that contain documents, which are basically JSON files. So let’s connect to the user collection, which will create itself the first time we access it.

mongodb.MongoClient.connect(uri, function(err, db) {
  const collection = db.collection('users')
  // ...
}
Copy the code

First, we’ll deal with the path to the POST method, which adds a new user’s data to it. Then, we update with the path of the PUT method.

App.post ("/:user", function (request, response) {// Insert a new document on the server collection.insertone ({... request.body, user : request.params.user }, function (err, r) { if (err){ response.send("An error occured") }else{ response.send("All well") } }) });Copy the code

The collection.insertone method of the collection adds a new document to the collection. In our example, each user has a separate document.

{… The request.body, user: request.params.user} parameter uses the expansion operator to merge the data in the request body content with the user data obtained from the URL.

The result is that the document is saved in the collection.

The second argument is a callback function that simply notifies the user of the result of the operation.

Get data from the database

Now that we have some data on the server, we want to read it. We use the GET method to read.

app.get("/:user", function (request, response) {
  collection.find({ user : request.params.user }).toArray(function (err, docs) {
    if (err){
      response.send("An error occured") 
    }else{
      response.send(docs)
    }
  })
});
Copy the code

This time, the first parameter is a filter that tells the database to send back only documents that match the user’s attributes.

The document returned to the user is a list, because theoretically more than one document could have attributes for that user. It’s up to us to make sure we only return one.

Update the data in the database

Finally, the PUT method can be used to update existing user data.

App. put("/:user", function (request, response) {collection.updateOne({user: request.params.user }, {$set:{ ... request.body, user : request.params.user }}, function (err, r) { if (err){ response.send("An error occured") }else{ response.send("All well") } }) });Copy the code

The first argument is a filter, just like in the GET method.

The second parameter is an update document. See here to learn more. In this example, we tell the database to merge the data that the user sends in with the existing data.

Be careful, though, because nested parameters will be replaced, not merged.

goodbye

This article is far from complete as a database and background programming guide, but it should be enough to get you started on building a database and provide some help for your personal projects.

In a future article, I might write about authentication. Until then, please do not use this database to store sensitive data.

Here, you can tinker with the project. Of course, you need to have your own database. If you haven’t already, refer back to the section setting up a database.

If you like this article, please give some applause so that more people can see it. Thank you very much!