concept database in category node

appears as: database, database, databases, A database, databases, The database
Get Programming with Node.js

This is an excerpt from Manning's book Get Programming with Node.js.

  • Unit 3 guides you through connecting your application to a database. This unit also helps you install a few new tools and structure your database with MongoDB.
  • Unit 4 teaches you about building data models in your application, where CRUD operations are performed to create, read, update, and delete data from the database.
  • When I have a database in place, Confetti Cuisine is comfortable with moving to the next stages of building user accounts. To accomplish this task, I need to build an application with

    Next, I need to build out how my data should look before it goes into the database.

    Getting MEAN with Mongo, Express, Angular, and Node.js 2ED

    This is an excerpt from Manning's book Getting MEAN with Mongo, Express, Angular, and Node.js 2ED.

    MongoDB’s flexibility in what it stores in documents is a great thing for the database. But most applications need some structure to their data. Note that the application needs structure, not the database. So where does it make most sense to define the structure of your application data? In the application itself!

    For storing the data, you’ll need a database—specifically, MongoDB. This step is the next one in the process: creating a database and a data model.

    You’ll start by connecting your application to a database before using Mongoose to define schemas and models. When you’re happy with the structure, you can add some test data directly to the MongoDB database. The final step is making sure that access to the data store also works when pushed up to Heroku. Figure 5.2 shows the flow of these four steps.

    Figure 5.2. Four main steps in this chapter, from connecting your application to a database to pushing the whole thing into a live environment

    For those of you who are worried that you’ve missed a section or two, don’t worry; you haven’t created a database yet. And you don’t need to. In various other technology stacks, this situation can present an issue and throw errors. But with MongoDB, you don’t need to create a database before connecting to it. MongoDB creates a database when you first try to use it. Figure 5.3 shows where this chapter focuses in terms of overall architecture.

    Figure 5.3. Viewing the MongoDB database and using Mongoose inside Express to model the data and manage the connection to the database
  • Step 2: Bring this file into the application by requiring it in app.js. As the actual process of creating a connection between the application and the database can take a little while, you want to do this early in the setup. Amend the top part of app.js to look like the following code snippet (modifications in bold):
    const express = require('express');
    const path = require('path');
    const cookieParser = require('cookie-parser');
    const logger = require('morgan');
    const favicon = require('serve-favicon');
    require('./app_server/models/db');
    !@%STYLE%@!
    {"css":"{\"css\": \"font-weight: bold;\"}","target":"[[{\"line\":5,\"ch\":0},{\"line\":5,\"ch\":34}]]"}
    !@%STYLE%@!
    
  • If you’re using an older version of MongoDB, you may see different messages, but it’s normally obvious if the command has worked or failed. You might also see a few lines starting with Server has startup warnings going on to state Access control is not enabled for the database. This isn’t anything to worry about on your local development machine.

    Serverless Applications with Node.js

    This is an excerpt from Manning's book Serverless Applications with Node.js.

    The last part of your serverless API is the data layer, which can be similar to the data layer in a scaled monolithic application, with a separately scaled database and file storage service. It would be best if the database and file storage were also independent and autoscalable.

    Listing 2.5 Your getPizzas handler with a pizza ID filter in a separate file
    const pizzas = require('../data/pizzas.json')    #1  
    
    function getPizzas(pizzaId) {    #2  
      if (!pizzaId)    #3  
        return pizzas
    
      const pizza = pizzas.find((pizza) => {    #4  
        return pizza.id == pizzaId    #5  
      })
    
      if (pizza)
        return pizza
    
      throw new Error('The pizza you requested was not found')    #6  
    }
    
    module.exports = getPizzas    #7  
    
      #1   Import the list of pizzas from the data directory.
      #2   Create the getPizzas handler function.
      #3   If a pizza ID is not passed, return the full pizza list.
      #4   Otherwise, search the list by the passed pizza ID.
      #5   Note == instead of ===. That’s because pizzaId is passed as a string, and you don’t want it to be a strict match, as in the database it may be an integer.
      #6   Throw an error if the application doesn’t find the selected pizza.
      #7   Export the getPizzas handler.

    Now that you have an idea of what to store, let’s see how you should structure it for the database. As you previously learned, you can’t rely on AWS Lambda to store state, which means that storing order information in your Lambda filesystem is off the table.

    Node.js in Action, Second Edition

    This is an excerpt from Manning's book Node.js in Action, Second Edition.

    Now let’s zoom into a specific aspect of figure 1.1: responding to browser requests. In this application, Node’s built-in HTTP server library, which is a core module called http.Server, handles the request by using a combination of streams, events, and Node’s HTTP request parser, which is native code. This triggers a callback in your application to run, which has been added using the Express (https://expressjs.com/) web application library. The callback that runs causes a database query to run, and eventually the application responds with JSON using HTTP. This whole process uses a minimum of three nonblocking network calls: one for the request, one for the database, and another for the response. How does Node schedule all these nonblocking network operations? The answer is the event loop. Figure 1.2 shows how the event loop is used for these three network operations.

    With the Postgres server running, a database created, and the pg package installed, you’re ready to start using the database from Node. Before you can issue any commands against the server, you need to establish a connection to it, as shown in the next listing.

    Listing 8.1. Connecting to the database

    LevelDB support in Node is provided by the LevelUP and LevelDOWN packages written by Node foundation chair and prolific Australian developer Rod Vagg. LevelDOWN is a simple, sugar-free C++ binding to LevelDB for Node, and it’s unlikely you’ll interface with it directly. LevelUP wraps the LevelDOWN API with a more convenient, idiomatic node interface, adding support for key/value encodings, JSON, buffering writes until the database is open, and wrapping the LevelDB iterator interface in a Node stream. Figure 8.5 shows levelup’s popularity on npm.

    8.2.2. Creating the database

    After the Postgres daemon is running, you need to create a database to use. This needs to be done only once. The simplest way is to use createdb from the command line. Here you create a database named articles:

    createdb articles

    There is no output if this succeeds. If a database with this name already exists, this command does nothing and reports a failure.

    Most applications connect to only a single database at a time, though multiple databases may be configured, depending on the environment the database is running in. Many applications have at least two environments: development and production.

    hapi.js in Action

    This is an excerpt from Manning's book hapi.js in Action.

    At the other end of the spectrum are micro-frameworks that do very little and make almost no decisions for you; they’re very thin wrappers around some native capability of the platform to offer convenient APIs for common tasks. A good example of such a framework is Express.js, a Node web framework. Express doesn’t offer its own solution for organizing code, input validation, or working with databases. All those things are possible but require you to make decisions yourself or interface with other bits of software.

    Listing 2.3. Querying a database for all recipes and printing each recipe’s name

    I’ve stored a random token for each user in the database. When a user attempts a request that requires authentication, the API goes through the steps in the following listing, in pseudocode.

    Listing 2.14. Authentication routine in pseudocode
    if(token exists in database) { authenticate user; load credentials; continue request; } else { reply 401 Unauthorized; }

    If you’re following along, you can use the database bundled with the supplied code for this book on GitHub (http://mng.bz/193e). Place the database file called dindin.sqlite at the root of your project directory, beside the index.js file.

    Node.js in Practice

    This is an excerpt from Manning's book Node.js in Practice.

    Streams are great for processing data, whether you’re reading, writing, or transforming it. Imagine you want to convert data from a database into another format, like CSV. You could create a stream class that accepts input from a database and outputs it as a stream of CSV. The output of this new CSV stream could be connected to an HTTP request, so you could stream CSV directly to a browser. The same class could even be connected to a writable file stream—you could even fork the stream to create a file and send it to a web browser.

    When you’re working in a team, you want to quickly see when someone has committed changes that break the tests. This section will help you to set up a continuous integration server so you can do this. It also has techniques for other project-related issues like using databases with tests and mocking web services.

    Listing 10.21. Stubbing a database