From 4b1a9203c547c019fc5398082ae19a3f3d4c3efe Mon Sep 17 00:00:00 2001 From: Peter Bengtsson Date: Tue, 8 Dec 2020 14:41:15 -0500 Subject: initial commit --- .../de/learn/server-side/erste_schritte/index.html | 49 ++ .../erste_schritte/introduction/index.html | 230 ++++++ .../de/learn/server-side/express_nodejs/index.html | 65 ++ .../server-side/express_nodejs/mongoose/index.html | 843 +++++++++++++++++++++ files/de/learn/server-side/index.html | 59 ++ 5 files changed, 1246 insertions(+) create mode 100644 files/de/learn/server-side/erste_schritte/index.html create mode 100644 files/de/learn/server-side/erste_schritte/introduction/index.html create mode 100644 files/de/learn/server-side/express_nodejs/index.html create mode 100644 files/de/learn/server-side/express_nodejs/mongoose/index.html create mode 100644 files/de/learn/server-side/index.html (limited to 'files/de/learn/server-side') diff --git a/files/de/learn/server-side/erste_schritte/index.html b/files/de/learn/server-side/erste_schritte/index.html new file mode 100644 index 0000000000..d2a3cc75ca --- /dev/null +++ b/files/de/learn/server-side/erste_schritte/index.html @@ -0,0 +1,49 @@ +--- +title: Erste Schritte in serverseitiger Webseiten-Programmierung +slug: Learn/Server-side/Erste_Schritte +tags: + - Anfänger + - Einführung + - Lernen + - Serverseitige Programmierung +translation_of: Learn/Server-side/First_steps +--- +

{{LearnSidebar}}
+ In diesem Modul beantworten wir grundlegende Fragen zur serverseitigen Programmierung - "Was ist das?", "Worin unterscheidet sie sich von der clientseitigen Programmierung?" und "Warum ist sie so nützlich?". Danach geben wir Ihnen einen Überblick über einige der beliebtesten serverseitigen Web-Frameworks und beraten Sie, wie Sie das am besten geeignete Framework für die Erstellung Ihrer ersten Website auswählen können. Schließlich bieten wir auch noch einen Einführungsartikel über Webserver-Sicherheit.

+ +

 

+ +

Vorraussetzungen

+ +

Wenn Sie mit diesem Modul starten, müssen Sie keine Kenntnisse in der serverseitigen Website-Programmierung oder in irgendeiner anderen Art von Programmierung haben. 

+ +

Allerdings müssen Sie verstehen, "Wie das Web funktioniert". Wir empfehlen Ihnen, zuerst die folgenden Themen zu lesen:

+ + + +

Mit diesem grundlegenden Verständnis sind Sie bereit, sich durch die einzelnen Module in diesem Abschnitt zu arbeiten. 

+ +

Anleitungen

+ +
+
Einführung auf der Serverseite
+
+

Willkommen zum MDN Einsteigerkurs Server-seitige Programmierung! In diesem ersten Artikel betrachten wir die grundlegende serverseitige Programmierung und beantworten Fragen wie "Was ist das?", "Worin unterscheidet es sich von der clientseitigen Programmierung?" und "Warum ist es so nützlich?". Nachdem Sie diesen Artikel gelesen haben, werden Sie den Einfluss verstehen, den Websites durch serverseitige Programmierung erhalten.

+
+
Überblick über den Client-Server
+
+

Nachdem Sie nun den Zweck und die möglichen Vorteile der serverseitigen Programmierung kennen, werden wir jetzt im Detail untersuchen was passiert, wenn ein Server eine "dynamische Anforderung" von einem Browser erhält. Da die meisten serverseitigen Codes auf der Website Anfragen und Antworten auf ähnliche Weise behandeln, hilft Ihnen dies zu verstehen, was Sie beim Schreiben Ihres eigenen Codes tun müssen.

+
+
Serverseitige Webframeworks
+
Der letzte Artikel zeigte Ihnen was eine serverseitige Webanwendung tun muss, um auf Anfragen von einem Webbrowser zu reagieren. Nun zeigen wir Ihnen, wie Web-Frameworks diese Aufgaben vereinfachen können und helfen Ihnen, das richtige Framework für Ihre erste serverseitige Webanwendung auszuwählen.
+
Webseitensicherheit
+
Die Sicherheit der Website erfordert ständige Aufmerksamkeit in allen Aspekten des Designs und der Nutzung der Website. Dieser einleitende Artikel wird Sie nicht zu einem Guru für Websitensicherheit machen, aber er wird Ihnen helfen, die ersten wichtigen Schritte zu verstehen die Sie unternehmen können, um Ihre Webanwendung gegen die häufigsten Bedrohungen zu schützen.
+
+ +

Aufgaben

+ +

Dieses Modul "Übersicht" hat keine Aufgaben, da wir Ihnen noch keinen Code angezeigt haben. Wir hoffen, dass Sie an dieser Stelle ein gutes Verständnis dafür haben, welche Art von Funktionalität Sie mit serverseitiger Programmierung liefern können und Sie haben eine Entscheidung darüber getroffen, mit welchem serverseitigen Web-Framework Sie Ihre erste Website erstellen werden.

diff --git a/files/de/learn/server-side/erste_schritte/introduction/index.html b/files/de/learn/server-side/erste_schritte/introduction/index.html new file mode 100644 index 0000000000..2924655941 --- /dev/null +++ b/files/de/learn/server-side/erste_schritte/introduction/index.html @@ -0,0 +1,230 @@ +--- +title: Einführung auf der Serverseite +slug: Learn/Server-side/Erste_Schritte/Introduction +tags: + - Anfänger + - Einführung +translation_of: Learn/Server-side/First_steps/Introduction +--- +
{{LearnSidebar}}
+ +
{{NextMenu("Learn/Server-side/First_steps/Client-Server_overview", "Learn/Server-side/First_steps")}}
+ +

Willkommen zum Einsteigerkurs für serverseitige Programmierung! In diesem ersten Artikel schauen wir uns die serverseitige Programmierung im Überblick an, antworten auf Fragen wie "Was ist das?", "Wie unterscheidet es sich von der Client-Seitigen Programmierung?" und "Warum ist es so nützlich?" Nachdem Du diesen Artikel gelesen hast wirst Du den Einfluss verstehen, den Websites durch die serverseitige Programmierung erhalten.

+ + + + + + + + + + + + +
Vorraussetzungen:Grundlegende Computerkenntnisse. Ein grundlegendes Verständnis davon, was ein Webserver ist.
Ziel:Sich damit vertraut machen, was serverseitige Programmierung ist, was sie kann und wie sie sich von der clientseitigen Programmierung unterscheidet.
+ +

Die meisten großen Websites verwenden serverseitigen Code, um bei Bedarf verschiedene Daten dynamisch anzuzeigen, die im Allgemeinen aus einer auf einem Server gespeicherten Datenbank gezogen und an den Client gesendet werden, um über einen bestimmten Code (z.B. HTML und JavaScript) angezeigt zu werden.

+ +

Der wahrscheinlich größte Vorteil von serverseitigem Code liegt darin, dass man den Inhalt individuell für jeden Benutzer anpassen kann. Dadurch können zum Beispiel bestimmte Details oder Angebote einer Website für bestimmte User hervorgehoben werden. Des weiteren kann serverseitiger Code die Website benutzerfreundlicher machen, indem zum Beispiel Kreditkarteninformationen oder die Versandadresse für weitere Bestellungen gespeichert werden.

+ +

Serverseitiger Code wird auch benötigt, um Interaktionen des Benutzers zu ermöglichen. Hierdurch können z.B. Benachrichtigungen oder Updates per E-Mail oder andere Kanäle versendet werden. All diese Vorteile bringen eine bessere Verknüpfung zwischen Benutzer und Website.

+ +

In der heutigen Zeit des Webdevelopments wird es deshalb empfohlen sich auch mit der serverseitigen Programmierung von Websites auseinanderzusetzen.

+ +

What is server-side website programming?

+ +

Web browsers communicate with web servers using the HyperText Transfer Protocol ({{glossary("HTTP")}}). When you click a link on a web page, submit a form, or run a search, an HTTP request is sent from your browser to the target server.

+ +

The request includes a URL identifying the affected resource, a method that defines the required action (for example to get, delete, or post the resource), and may include additional information encoded in URL parameters (the field-value pairs sent via a query string), as POST data (data sent by the HTTP POST method), or in associated {{glossary("Cookie", "cookies")}}.

+ +

Web servers wait for client request messages, process them when they arrive, and reply to the web browser with an HTTP response message. The response contains a status line indicating whether or not the request succeeded (e.g. "HTTP/1.1 200 OK" for success). 

+ +

The body of a successful response to a request would contain the requested resource (e.g. a new HTML page, or an image, etc...), which could then be displayed by the web browser.

+ +

Static sites

+ +

The diagram below shows a basic web server architecture for a static site (a static site is one that returns the same hard-coded content from the server whenever a particular resource is requested). When a user wants to navigate to a page, the browser sends an HTTP "GET" request specifying its URL.

+ +

The server retrieves the requested document from its file system and returns an HTTP response containing the document and a success status (usually 200 OK). If the file cannot be retrieved for some reason, an error status is returned (see client error responses and server error responses).

+ +

A simplified diagram of a static web server.

+ +

Dynamic sites

+ +

A dynamic website is one where some of the response content is generated dynamically only when needed. On a dynamic website HTML pages are normally created by inserting data from a database into placeholders in HTML templates (this is a much more efficient way of storing large amounts of content than using static websites). 

+ +

A dynamic site can return different data for a URL based on information provided by the user or stored preferences and can perform other operations as part of returning a response (e.g. sending notifications).

+ +

Most of the code to support a dynamic website must run on the server. Creating this code is known as "server-side programming" (or sometimes "back-end scripting").

+ +

The diagram below shows a simple architecture for a dynamic website. As in the previous diagram, browsers send HTTP requests to the server, then the server processes the requests and returns appropriate HTTP responses.

+ +

Requests for static resources are handled in the same way as for static sites (static resources are any files that don't change —typically: CSS, JavaScript, Images, pre-created PDF files etc). 

+ +

A simplified diagram of a web server that uses server-side programming to get information from a database and construct HTML from templates. This is the same diagram as is in the Client-Server overview.

+ +

Requests for dynamic resources are instead forwarded (2) to server-side code (shown in the diagram as a Web Application). For "dynamic requests" the server interprets the request, reads required information from the database (3), combines the retrieved data with HTML templates (4), and sends back a response containing the generated HTML (5,6). 

+ +
+

Are server-side and client-side programming the same?

+
+ +

Let's now turn our attention to the code involved in server-side and client-side programming. In each case, the code is significantly different:

+ + + +

Code running in the browser is known as client-side code and is primarily concerned with improving the appearance and behavior of a rendered web page. This includes selecting and styling UI components, creating layouts, navigation, form validation, etc. By contrast, server-side website programming mostly involves choosing which content is returned to the browser in response to requests. The server-side code handles tasks like validating submitted data and requests, using databases to store and retrieve data and sending the correct data to the client as required.

+ +

Client-side code is written using HTMLCSS, and JavaScript — it is run inside a web browser and has little or no access to the underlying operating system (including limited access to the file system).

+ +

Web developers can't control what browser every user might be using to view a website  — browsers provide inconsistent levels of compatibility with client-side code features, and part of the challenge of client-side programming is handling differences in browser support gracefully.

+ +

Server-side code can be written in any number of programming languages — examples of popular server-side web languages include PHP, Python, Ruby, C#, and NodeJS(JavaScript). The server-side code has full access to the server operating system and the developer can choose what programming language (and specific version) they wish to use.

+ +

Developers typically write their code using web frameworks. Web frameworks are collections of functions, objects, rules and other code constructs designed to solve common problems, speed up development, and simplify the different types of tasks faced in a particular domain.

+ +

Again, while both client and server-side code use frameworks, the domains are very different, and hence so are the frameworks. Client-side web frameworks simplify layout and presentation tasks while server-side web frameworks provide a lot of “common” web server functionality that you might otherwise have to implement yourself (e.g. support for sessions, support for users and authentication, easy database access, templating libraries, etc.).

+ +
+

Note: Client-side frameworks are often used to help speed up development of client-side code, but you can also choose to write all the code by hand; in fact, writing your code by hand can be quicker and more efficient if you only need a small, simple web site UI.

+ +

In contrast, you would almost never consider writing the server-side component of a web app without a framework — implementing a vital feature like an HTTP server is really hard to do from scratch in say Python, but Python web frameworks like Django provide one out of the box, along with other very useful tools.

+
+ +
+

What can you do on the server-side?

+ +

Server-side programming is very useful because it allows us to efficiently deliver information tailored for individual users and thereby create a much better user experience.

+
+ +

Companies like Amazon use server-side programming to construct search results for products, make targeted product suggestions based on client preferences and previous buying habits, simplify purchases, etc.

+ +

Banks use server-side programming to store account information and allow only authorized users to view and make transactions. Other services like Facebook, Twitter, Instagram, and Wikipedia use server-side programming to highlight, share, and control access to interesting content.

+ +

Some of the common uses and benefits of server-side programming are listed below. You'll note that there is some overlap!

+ +

Efficient storage and delivery of information

+ +

Imagine how many products are available on Amazon, and imagine how many posts have been written on Facebook? Creating a separate static page for each product or post would be completely impractical.

+ +

Server-side programming allows us to instead store the information in a database and dynamically construct and return HTML and other types of files (e.g. PDFs, images, etc.). It is also possible to simply return data ({{glossary("JSON")}}, {{glossary("XML")}}, etc.) for rendering by appropriate client-side web frameworks (this reduces the processing burden on the server and the amount of data that needs to be sent).

+ +

The server is not limited to sending information from databases, and might alternatively return the result of software tools, or data from communications services. The content can even be targeted for the type of client device that is receiving it.

+ +

Because the information is in a database, it can also more easily be shared and updated with other business systems (for example, when products are sold either online or in a shop, the shop might update its database of inventory).

+ +
+

Note: Your imagination doesn't have to work hard to see the benefit of server-side code for efficient storage and delivery of information:

+ +
    +
  1. Go to Amazon or some other e-commerce site.
  2. +
  3. Search for a number of keywords and note how the page structure doesn't change, even though the results do. 
  4. +
  5. Open two or three different products. Note again how they have a common structure and layout, but the content for different products has been pulled from the database.
  6. +
+ +

For a common search term ("fish", say) you can see literally millions of returned values. Using a database allows these to be stored and shared efficiently, and it allows the presentation of the information to be controlled in just one place.

+
+ +

Customised user experience

+ +

Servers can store and use information about clients to provide a convenient and tailored user experience. For example, many sites store credit cards so that details don't have to be entered again. Sites like Google Maps can use saved or current locations for providing routing information, and search or travel history to highlight local businesses in search results.

+ +

A deeper analysis of user habits can be used to anticipate their interests and further customize responses and notifications, for example providing a list of previously visited or popular locations you may want to look at on a map.

+ +
+

Note: Google Maps saves your search and visit history. Frequently visited or frequently searched locations are highlighted more than others.

+ +

Google search results are optimized based on previous searches.

+ +
    +
  1.  Go to Google search.
  2. +
  3.  Search for "football".
  4. +
  5.  Now try typing "favourite" in the search box and observe the autocomplete search predictions.
  6. +
+ +

Coincidence? Nada!

+
+ +

Controlled access to content

+ +

Server-side programming allows sites to restrict access to authorized users and serve only the information that a user is permitted to see.

+ +

Real world examples include:

+ + + +
+

Note: Consider other real examples where access to content is controlled. For example, what can you see if you go to the online site for your bank? Log in to your account — what additional information can you see and modify? What information can you see that only the bank can change?

+
+ +

Store session/state information

+ +

Server-side programming allows developers to make use of sessions — basically, a mechanism that allows a server to store information on the current user of a site and send different responses based on that information.

+ +

This allows, for example, a site to know that a user has previously logged in and display links to their emails or order history, or perhaps save the state of a simple game so that the user can go to a site again and carry on where they left it.

+ +
+

Note: Visit a newspaper site that has a subscription model and open a bunch of tabs (e.g. The Age). Continue to visit the site over a few hours/days. Eventually, you will start to be redirected to pages explaining how to subscribe, and you will be unable to access articles. This information is an example of session information stored in cookies.

+
+ +

Notifications and communication

+ +

Servers can send general or user-specific notifications through the website itself or via email, SMS, instant messaging, video conversations, or other communications services.

+ +

A few examples include:

+ + + +
+

Note: The most common type of notification is a "confirmation of registration". Pick almost any large site that you are interested in (Google, Amazon, Instagram, etc.) and create a new account using your email address. You will shortly receive an email confirming your registration, or requiring acknowledgment to activate your account.

+
+ +

Data analysis

+ +

A website may collect a lot of data about users: what they search for, what they buy, what they recommend, how long they stay on each page. Server-side programming can be used to refine responses based on analysis of this data.

+ +

For example, Amazon and Google both advertise products based on previous searches (and purchases).

+ +
+

Note: If you're a Facebook user, go to your main feed and look at the stream of posts. Note how some of the posts are out of numerical order - in particular, posts with more "likes" are often higher on the list than more recent posts.

+ +

Also look at what kind of ads you are being shown — you might see ads for things you looked at on other sites. Facebook's algorithm for highlighting content and advertising can be a bit of a mystery, but it is clear that it does depend on your likes and viewing habits!

+
+ +

Summary

+ +

Congratulations, you've reached the end of the first article about server-side programming. 

+ +

You've now learned that server-side code is run on a web server and that its main role is to control what information is sent to the user (while client-side code mainly handles the structure and presentation of that data to the user).

+ +

You should also understand that it is useful because it allows us to create websites that efficiently deliver information tailored for individual users and have a good idea of some of the things you might be able to do when you're a server-side programmer.

+ +

Lastly, you should understand that server-side code can be written in a number of programming languages and that you should use a web framework to make the whole process easier. 

+ +

In a future article we'll help you choose the best web framework for your first site; Next, though we'll take you through the main client-server interactions in just a little more detail.

+ +

{{NextMenu("Learn/Server-side/First_steps/Client-Server_overview", "Learn/Server-side/First_steps")}}

+ +

In this module

+ + diff --git a/files/de/learn/server-side/express_nodejs/index.html b/files/de/learn/server-side/express_nodejs/index.html new file mode 100644 index 0000000000..7462f8c23f --- /dev/null +++ b/files/de/learn/server-side/express_nodejs/index.html @@ -0,0 +1,65 @@ +--- +title: Express Web Anwendungsrahmen (Node.js/JavaScript) +slug: Learn/Server-side/Express_Nodejs +translation_of: Learn/Server-side/Express_Nodejs +--- +
{{LearnSidebar}}
+Express ist ein beliebter, weitgehend vorgabefreier Anwendungsbausatz (Framework) für das Web, das in Javascript geschrieben und in der Node.js Laufzeitumgebung beheimatet ist. Das Modul beschreibt einige Schlüsselvorteile dieses Anwendungsrahmens, wie eine Anwendungsumgebung aufzusetzen ist und wie allgemeine Entwicklungs- und Bereitstellungsaufgaben durchzuführen sind.
+ +

Voraussetzungen

+ +

Bevor Sie dies Modul beginnen sollten Sie verstehen, was serverseitige Web-Anwendungsentwicklung und Web Frameworks sind – idealerweise durch Studium unseres Moduls Erste Schritte Server-side Website Programmierung.
+ Allgemeine Kenntnisse in Programmierung und Javascript werden vorausgesetzt, sind aber zum Verständnis der grundlegenden Konzepte nicht ausschlaggebend.

+ +
+

Anmerkung: Diese Website bietet zahlreiche Quellen zum Lernen von Javascript im Kontext Client-seitiger EntwicklungJavascriptJavascript Guide, Javascript BasicsJavascript (Lernen). Der Kern von Javascript und seine Konzepte sind identisch für Server-seitige Entwicklung mit Node.js und dieses Material ist daher relevant.
+ Node.js bietet Schnittstellen/APIs zur Unterstützung von Funktionalitäten, die in einer Umgebung ohne Browser nützlich sind, z.B. um HTTP Server zu bauen oder auf das Dateisystem zuzugreifen, aber es unterstützt keine Javascript APIs zur Interaktion mit Browser oder DOM.

+ +

Dieser Leitfaden bietet Informationen zum Umgang mit Node.js und Express. Darüber hinaus gibt es ausgezeichnete Informationsquellen im Internet und in Form von Fachbüchern – Links sind u.a. hier zu finden: How do I get started with Node.js (StackOverflow) und What are the best resources for learning Node.js? (Quora).

+
+ +

Leitfaden

+ +
+
Express/Node Einführung
+
Im ersten Artikel zum Thema Express werden die Fragen beantwortet "Was ist Node?" und "Was ist Express?", außerdem beleuchtet er die Besonderheiten des Express Web Frameworks. Wir werden die wichtigsten Eigenschaften sowie die Grundbausteine einer Express Anwendung kennen lernen (auch wenn wir hier noch keine Entwicklungsumgebung zum Testen aufsetzen werden).
+
Aufsetzen einer Node (Express) Entwicklungsumgebung
+
Now that you know what Express is for, we'll show you how to set up and test a Node/Express development environment on Windows, Linux (Ubuntu), and Mac OS X. Whatever common operating system you are using, this article should give you what you need to be able to start developing Express apps.
+
Express Tutorial: The Local Library website
+
The first article in our practical tutorial series explains what you'll learn and provides an overview of the "local library" example website we'll be working through and evolving in subsequent articles.
+
Express Tutorial Part 2: Creating a skeleton website
+
This article shows how you can create a "skeleton" website project, which you can then go on to populate with site-specific routes, templates/views, and databases.
+
Express Tutorial Part 3: Using a Database (with Mongoose)
+
This article briefly introduces databases for Node/Express. It then goes on to show how we can use Mongoose to provide database access for the LocalLibrary website. It explains how object schema and models are declared, the main field types, and basic validation. It also briefly shows a few of the main ways you can access model data.
+
Express Tutorial Part 4: Routes and controllers
+
In this tutorial we'll set up routes (URL handling code) with "dummy" handler functions for all the resource endpoints that we'll eventually need in the LocalLibrary website. On completion, we'll have a modular structure for our route handling code, that we can extend with real handler functions in the following articles. We'll also have a really good understanding of how to create modular routes using Express.
+
Express Tutorial Part 5: Displaying library data
+
We're now ready to add the pages that display the LocalLibrary website books and other data. The pages will include a home page that shows how many records we have of each model type and list and detail pages for all of our models. Along the way, we'll gain practical experience in getting records from the database and using templates.
+
Express Tutorial Part 6: Working with forms
+
In this tutorial we'll show you how to work with HTML Forms in Express, using Pug, and in particular how to write forms to create, update, and delete documents from the database.
+
Express Tutorial Part 7: Deploying to production
+
Now you've created an awesome LocalLibrary website, you're going to want to install it on a public web server so that it can be accessed by library staff and members over the Internet. This article provides an overview of how you might go about finding a host to deploy your website, and what you need to do in order to get your site ready for production.
+
+ +

See also

+ +
+
Installing LocalLibrary on PWS/Cloud Foundry
+
This article provides a practical demonstration of how to install LocalLibrary on the Pivotal Web Services PaaS cloud — this is a full-featured, open source alternative to Heroku, the PaaS cloud service used in Part 7 of the tutorial, listed above. PWS/Cloud Foundry is definitely worth checking out if you are looking for an alternative to Heroku (or another PaaS cloud service), or simply feel like trying something different.
+
+ +

Adding more tutorials

+ +
+

That's the end of the tutorial articles (for now). If you would like to extend it, other interesting topics to cover are:

+ + + +

And of course, it would be excellent to have an assessment task!

+
diff --git a/files/de/learn/server-side/express_nodejs/mongoose/index.html b/files/de/learn/server-side/express_nodejs/mongoose/index.html new file mode 100644 index 0000000000..525764221c --- /dev/null +++ b/files/de/learn/server-side/express_nodejs/mongoose/index.html @@ -0,0 +1,843 @@ +--- +title: 'Express Tutorial Part 3: Nutzung einer Datenbank (Mit Mongoose)' +slug: Learn/Server-side/Express_Nodejs/mongoose +translation_of: Learn/Server-side/Express_Nodejs/mongoose +--- +
{{LearnSidebar}}
+ +
{{PreviousMenuNext("Learn/Server-side/Express_Nodejs/skeleton_website", "Learn/Server-side/Express_Nodejs/routes", "Learn/Server-side/Express_Nodejs")}}
+ +

This article briefly introduces databases, and how to use them with Node/Express apps. It then goes on to show how we can use Mongoose to provide database access for the LocalLibrary website. It explains how object schema and models are declared, the main field types, and basic validation. It also briefly shows a few of the main ways in which you can access model data.

+ + + + + + + + + + + + +
Prerequisites:Express Tutorial Part 2: Creating a skeleton website
Objective:To be able to design and create your own models using Mongoose.
+ +

Overview

+ +

Library staff will use the Local Library website to store information about books and borrowers, while library members will use it to browse and search for books, find out whether there are any copies available, and then reserve or borrow them. In order to store and retrieve information efficiently, we will store it in a database.

+ +

Express apps can use many different databases, and there are several approaches you can use for performing Create, Read, Update and Delete (CRUD) operations. This tutorial provides a brief overview of some of the available options and then goes on to show in detail the particular mechanisms selected.

+ +

What databases can I use?

+ +

Express apps can use any database supported by Node (Express itself doesn't define any specific additional behavior/requirements for database management). There are many popular options, including PostgreSQL, MySQL, Redis, SQLite, and MongoDB.

+ +

When choosing a database, you should consider things like time-to-productivity/learning curve, performance, ease of replication/backup, cost, community support, etc. While there is no single "best" database, almost any of the popular solutions should be more than acceptable for a small-to-medium-sized site like our Local Library.

+ +

For more information on the options see Database integration (Express docs).

+ +

What is the best way to interact with a database?

+ +

There are two common approaches for interacting with a database: 

+ + + +

The very best performance can be gained by using SQL, or whatever query language is supported by the database. ODM's are often slower because they use translation code to map between objects and the database format, which may not use the most efficient database queries (this is particularly true if the ODM supports different database backends, and must make greater compromises in terms of what database features are supported).

+ +

The benefit of using an ORM is that programmers can continue to think in terms of JavaScript objects rather than database semantics — this is particularly true if you need to work with different databases (on either the same or different websites). They also provide an obvious place to perform data validation.

+ +
+

Tip:  Using ODM/ORMs often results in lower costs for development and maintenance! Unless you're very familiar with the native query language or performance is paramount, you should strongly consider using an ODM.

+
+ +

What ORM/ODM should I use?

+ +

There are many ODM/ORM solutions available on the NPM package manager site (check out the odm and orm tags for a subset!).

+ +

A few solutions that were popular at the time of writing are:

+ + + +

As a general rule, you should consider both the features provided and the "community activity" (downloads, contributions, bug reports, quality of documentation, etc.) when selecting a solution. At the time of writing Mongoose is by far the most popular ODM, and is a reasonable choice if you're using MongoDB for your database.

+ +

Using Mongoose and MongoDb for the LocalLibrary

+ +

For the Local Library example (and the rest of this topic) we're going to use the Mongoose ODM to access our library data. Mongoose acts as a front end to MongoDB, an open source NoSQL database that uses a document-oriented data model. A “collection” of “documents” in a MongoDB database is analogous to a “table” of “rows” in a relational database.

+ +

This ODM and database combination is extremely popular in the Node community, partially because the document storage and query system looks very much like JSON, and is hence familiar to JavaScript developers.

+ +
+

Tip: You don't need to know MongoDB in order to use Mongoose, although parts of the Mongoose documentation are easier to use and understand if you are already familiar with MongoDB.

+
+ +

The rest of this tutorial shows how to define and access the Mongoose schema and models for the LocalLibrary website example.

+ +

Designing the LocalLibrary models

+ +

Before you jump in and start coding the models, it's worth taking a few minutes to think about what data we need to store and the relationships between the different objects.

+ +

We know that we need to store information about books (title, summary, author, genre, ISBN) and that we might have multiple copies available (with globally unique ids, availability statuses, etc.). We might need to store more information about the author than just their name, and there might be multiple authors with the same or similar names. We want to be able to sort information based on the book title, author, genre, and category.

+ +

When designing your models it makes sense to have separate models for every "object" (a group of related information). In this case some obvious candidates for these models are books, book instances, and authors.

+ +

You might also want to use models to represent selection-list options (e.g. like a drop-down list of choices), rather than hard-coding the choices into the website itself — this is recommended when all the options aren't known up front or may change. A good example is a genre (e.g. fantasy, science fiction, etc.).

+ +

Once we've decided on our models and fields, we need to think about the relationships between them.

+ +

With that in mind, the UML association diagram below shows the models we'll define in this case (as boxes). As discussed above, we've created models for the book (the generic details of the book), book instance (status of specific physical copies of the book available in the system), and author. We have also decided to have a model for the genre so that values can be created dynamically. We've decided not to have a model for the BookInstance:status — we will hard code the acceptable values because we don't expect these to change. Within each of the boxes, you can see the model name, the field names and types, and also the methods and their return types.

+ +

The diagram also shows the relationships between the models, including their multiplicities. The multiplicities are the numbers on the diagram showing the numbers (maximum and minimum) of each model that may be present in the relationship. For example, the connecting line between the boxes shows that Book and a Genre are related. The numbers close to the Book model show that a Genre must have zero or more Books (as many as you like), while the numbers on the other end of the line next to the Genre show that a book can have zero or more associated Genres.

+ +
+

Note: As discussed in our Mongoose primer below it is often better to have the field that defines the relationship between the documents/models in just one model (you can still find the reverse relationship by searching for the associated _id in the other model). Below we have chosen to define the relationship between Book/Genre and Book/Author in the Book schema, and the relationship between the Book/BookInstance in the BookInstance Schema. This choice was somewhat arbitrary — we could equally well have had the field in the other schema.

+
+ +

Mongoose Library Model  with correct cardinality

+ +
+

Note: The next section provides a basic primer explaining how models are defined and used. As you read it, consider how we will construct each of the models in the diagram above.

+
+ +

Mongoose primer

+ +

This section provides an overview of how to connect Mongoose to a MongoDB database, how to define a schema and a model, and how to make basic queries. 

+ +
+

Note: This primer is heavily influenced by the Mongoose quick start on npm and the official documentation.

+
+ +

Installing Mongoose and MongoDB

+ +

Mongoose is installed in your project (package.json) like any other dependency — using NPM. To install it, use the following command inside your project folder:

+ +
npm install mongoose
+
+ +

Installing Mongoose adds all its dependencies, including the MongoDB database driver, but it does not install MongoDB itself. If you want to install a MongoDB server then you can download installers from here for various operating systems and install it locally. You can also use cloud-based MongoDB instances.

+ +
+

Note: For this tutorial, we'll be using the MongoDB Atlas cloud-based database as a service free tier to provide the database. This is suitable for development and makes sense for the tutorial because it makes "installation" operating system independent (database-as-a-service is also one approach you might use for your production database).

+
+ +

Connecting to MongoDB

+ +

Mongoose requires a connection to a MongoDB database. You can require() and connect to a locally hosted database with mongoose.connect(), as shown below.

+ +
//Import the mongoose module
+var mongoose = require('mongoose');
+
+//Set up default mongoose connection
+var mongoDB = 'mongodb://127.0.0.1/my_database';
+mongoose.connect(mongoDB, { useNewUrlParser: true });
+
+//Get the default connection
+var db = mongoose.connection;
+
+//Bind connection to error event (to get notification of connection errors)
+db.on('error', console.error.bind(console, 'MongoDB connection error:'));
+ +

You can get the default Connection object with mongoose.connection. Once connected, the open event is fired on the Connection instance.

+ +
+

Tip: If you need to create additional connections you can use mongoose.createConnection(). This takes the same form of database URI (with host, database, port, options etc.) as connect() and returns a Connection object).

+
+ +

Defining and creating models

+ +

Models are defined using the Schema interface. The Schema allows you to define the fields stored in each document along with their validation requirements and default values. In addition, you can define static and instance helper methods to make it easier to work with your data types, and also virtual properties that you can use like any other field, but which aren't actually stored in the database (we'll discuss a bit further below).

+ +

Schemas are then "compiled" into models using the mongoose.model() method. Once you have a model you can use it to find, create, update, and delete objects of the given type.

+ +
+

Note: Each model maps to a collection of documents in the MongoDB database. The documents will contain the fields/schema types defined in the model Schema.

+
+ +

Defining schemas

+ +

The code fragment below shows how you might define a simple schema. First you require() mongoose, then use the Schema constructor to create a new schema instance, defining the various fields inside it in the constructor's object parameter.

+ +
//Require Mongoose
+var mongoose = require('mongoose');
+
+//Define a schema
+var Schema = mongoose.Schema;
+
+var SomeModelSchema = new Schema({
+  a_string: String,
+  a_date: Date
+});
+
+ +

In the case above we just have two fields, a string and a date. In the next sections, we will show some of the other field types, validation, and other methods.

+ +

Creating a model

+ +

Models are created from schemas using the mongoose.model() method:

+ +
// Define schema
+var Schema = mongoose.Schema;
+
+var SomeModelSchema = new Schema({
+  a_string: String,
+  a_date: Date
+});
+
+// Compile model from schema
+var SomeModel = mongoose.model('SomeModel', SomeModelSchema );
+ +

The first argument is the singular name of the collection that will be created for your model (Mongoose will create the database collection for the above model SomeModel above), and the second argument is the schema you want to use in creating the model.

+ +
+

Note: Once you've defined your model classes you can use them to create, update, or delete records, and run queries to get all records or particular subsets of records. We'll show you how to do this in the Using models section, and when we create our views.

+
+ +

Schema types (fields)

+ +

A schema can have an arbitrary number of fields — each one represents a field in the documents stored in MongoDB. An example schema showing many of the common field types and how they are declared is shown below.

+ +
var schema = new Schema(
+{
+  name: String,
+  binary: Buffer,
+  living: Boolean,
+  updated: { type: Date, default: Date.now() },
+  age: { type: Number, min: 18, max: 65, required: true },
+  mixed: Schema.Types.Mixed,
+  _someId: Schema.Types.ObjectId,
+  array: [],
+  ofString: [String], // You can also have an array of each of the other types too.
+  nested: { stuff: { type: String, lowercase: true, trim: true } }
+})
+ +

Most of the SchemaTypes (the descriptors after “type:” or after field names) are self-explanatory. The exceptions are:

+ + + +

The code also shows both ways of declaring a field:

+ + + +

For more information about options see SchemaTypes (Mongoose docs).

+ +

Validation

+ +

Mongoose provides built-in and custom validators, and synchronous and asynchronous validators. It allows you to specify both the acceptable range of values and the error message for validation failure in all cases.

+ +

The built-in validators include:

+ + + +

The example below (slightly modified from the Mongoose documents) shows how you can specify some of the validator types and error messages:

+ +
var breakfastSchema = new Schema({
+  eggs: {
+    type: Number,
+    min: [6, 'Too few eggs'],
+    max: 12,
+    required: [true, 'Why no eggs?']
+  },
+  drink: {
+    type: String,
+    enum: ['Coffee', 'Tea', 'Water',]
+  }
+});
+
+ +

For complete information on field validation see Validation (Mongoose docs).

+ +

Virtual properties

+ +

Virtual properties are document properties that you can get and set but that do not get persisted to MongoDB. The getters are useful for formatting or combining fields, while setters are useful for de-composing a single value into multiple values for storage. The example in the documentation constructs (and deconstructs) a full name virtual property from a first and last name field, which is easier and cleaner than constructing a full name every time one is used in a template.

+ +
+

Note: We will use a virtual property in the library to define a unique URL for each model record using a path and the record's _id value.

+
+ +

For more information see Virtuals (Mongoose documentation).

+ +

Methods and query helpers

+ +

A schema can also have instance methods, static methods, and query helpers. The instance and static methods are similar, but with the obvious difference that an instance method is associated with a particular record and has access to the current object. Query helpers allow you to extend mongoose's chainable query builder API (for example, allowing you to add a query "byName" in addition to the find(), findOne() and findById() methods).

+ +

Using models

+ +

Once you've created a schema you can use it to create models. The model represents a collection of documents in the database that you can search, while the model's instances represent individual documents that you can save and retrieve.

+ +

We provide a brief overview below. For more information see: Models (Mongoose docs).

+ +

Creating and modifying documents

+ +

To create a record you can define an instance of the model and then call save(). The examples below assume SomeModel is a model (with a single field "name") that we have created from our schema.

+ +
// Create an instance of model SomeModel
+var awesome_instance = new SomeModel({ name: 'awesome' });
+
+// Save the new model instance, passing a callback
+awesome_instance.save(function (err) {
+  if (err) return handleError(err);
+  // saved!
+});
+
+ +

Creation of records (along with updates, deletes, and queries) are asynchronous operations — you supply a callback that is called when the operation completes. The API uses the error-first argument convention, so the first argument for the callback will always be an error value (or null). If the API returns some result, this will be provided as the second argument.

+ +

You can also use create() to define the model instance at the same time as you save it. The callback will return an error for the first argument and the newly-created model instance for the second argument.

+ +
SomeModel.create({ name: 'also_awesome' }, function (err, awesome_instance) {
+  if (err) return handleError(err);
+  // saved!
+});
+ +

Every model has an associated connection (this will be the default connection when you use mongoose.model()). You create a new connection and call .model() on it to create the documents on a different database.

+ +

You can access the fields in this new record using the dot syntax, and change the values. You have to call save() or update() to store modified values back to the database.

+ +
// Access model field values using dot notation
+console.log(awesome_instance.name); //should log 'also_awesome'
+
+// Change record by modifying the fields, then calling save().
+awesome_instance.name="New cool name";
+awesome_instance.save(function (err) {
+   if (err) return handleError(err); // saved!
+});
+
+ +

Searching for records

+ +

You can search for records using query methods, specifying the query conditions as a JSON document. The code fragment below shows how you might find all athletes in a database that play tennis, returning just the fields for athlete name and age. Here we just specify one matching field (sport) but you can add more criteria, specify regular expression criteria, or remove the conditions altogether to return all athletes.

+ +
var Athlete = mongoose.model('Athlete', yourSchema);
+
+// find all athletes who play tennis, selecting the 'name' and 'age' fields
+Athlete.find({ 'sport': 'Tennis' }, 'name age', function (err, athletes) {
+  if (err) return handleError(err);
+  // 'athletes' contains the list of athletes that match the criteria.
+})
+ +

If you specify a callback, as shown above, the query will execute immediately. The callback will be invoked when the search completes.

+ +
+

Note: All callbacks in Mongoose use the pattern callback(error, result). If an error occurs executing the query, the error parameter will contain an error document and result will be null. If the query is successful, the error parameter will be null, and the result will be populated with the results of the query.

+
+ +
+

Note: It is important to remember that not finding any results is not an error for a search —but it may be a fail-case in the context of your application. If your application expects a search to find a value you can either check the result in the callback (results==null) or daisy chain the orFail() method on the query. 

+
+ +

If you don't specify a callback then the API will return a variable of type Query. You can use this query object to build up your query and then execute it (with a callback) later using the exec() method.

+ +
// find all athletes that play tennis
+var query = Athlete.find({ 'sport': 'Tennis' });
+
+// selecting the 'name' and 'age' fields
+query.select('name age');
+
+// limit our results to 5 items
+query.limit(5);
+
+// sort by age
+query.sort({ age: -1 });
+
+// execute the query at a later time
+query.exec(function (err, athletes) {
+  if (err) return handleError(err);
+  // athletes contains an ordered list of 5 athletes who play Tennis
+})
+ +

Above we've defined the query conditions in the find() method. We can also do this using a where() function, and we can chain all the parts of our query together using the dot operator (.) rather than adding them separately. The code fragment below is the same as our query above, with an additional condition for the age.

+ +
Athlete.
+  find().
+  where('sport').equals('Tennis').
+  where('age').gt(17).lt(50).  //Additional where query
+  limit(5).
+  sort({ age: -1 }).
+  select('name age').
+  exec(callback); // where callback is the name of our callback function.
+ +

The find() method gets all matching records, but often you just want to get one match. The following methods query for a single record:

+ + + +
+

Note: There is also a count() method that you can use to get the number of items that match conditions. This is useful if you want to perform a count without actually fetching the records.

+
+ +

There is a lot more you can do with queries. For more information see: Queries (Mongoose docs).

+ + + +

You can create references from one document/model instance to another using the ObjectId schema field, or from one document to many using an array of ObjectIds. The field stores the id of the related model. If you need the actual content of the associated document, you can use the populate() method in a query to replace the id with the actual data.

+ +

For example, the following schema defines authors and stories. Each author can have multiple stories, which we represent as an array of ObjectId. Each story can have a single author. The "ref" (highlighted in bold below) tells the schema which model can be assigned to this field.

+ +
var mongoose = require('mongoose')
+  , Schema = mongoose.Schema
+
+var authorSchema = Schema({
+  name    : String,
+  stories : [{ type: Schema.Types.ObjectId, ref: 'Story' }]
+});
+
+var storySchema = Schema({
+  author : { type: Schema.Types.ObjectId, ref: 'Author' },
+  title    : String
+});
+
+var Story  = mongoose.model('Story', storySchema);
+var Author = mongoose.model('Author', authorSchema);
+ +

We can save our references to the related document by assigning the _id value. Below we create an author, then a story, and assign the author id to our story's author field.

+ +
var bob = new Author({ name: 'Bob Smith' });
+
+bob.save(function (err) {
+  if (err) return handleError(err);
+
+  //Bob now exists, so lets create a story
+  var story = new Story({
+    title: "Bob goes sledding",
+    author: bob._id    // assign the _id from the our author Bob. This ID is created by default!
+  });
+
+  story.save(function (err) {
+    if (err) return handleError(err);
+    // Bob now has his story
+  });
+});
+ +

Our story document now has an author referenced by the author document's ID. In order to get the author information in the story results we use populate(), as shown below.

+ +
Story
+.findOne({ title: 'Bob goes sledding' })
+.populate('author') //This populates the author id with actual author information!
+.exec(function (err, story) {
+  if (err) return handleError(err);
+  console.log('The author is %s', story.author.name);
+  // prints "The author is Bob Smith"
+});
+ +
+

Note: Astute readers will have noted that we added an author to our story, but we didn't do anything to add our story to our author's stories array. How then can we get all stories by a particular author? One way would be to add our story to the stories array, but this would result in us having two places where the information relating authors and stories needs to be maintained.

+ +

A better way is to get the _id of our author, then use find() to search for this in the author field across all stories.

+ +
Story
+.find({ author : bob._id })
+.exec(function (err, stories) {
+  if (err) return handleError(err);
+  // returns all stories that have Bob's id as their author.
+});
+
+
+ +

This is almost everything you need to know about working with related items for this tutorial. For more detailed information see Population (Mongoose docs).

+ +

One schema/model per file

+ +

While you can create schemas and models using any file structure you like, we highly recommend defining each model schema in its own module (file), then exporting the method to create the model. This is shown below:

+ +
// File: ./models/somemodel.js
+
+//Require Mongoose
+var mongoose = require('mongoose');
+
+//Define a schema
+var Schema = mongoose.Schema;
+
+var SomeModelSchema = new Schema({
+  a_string          : String,
+  a_date            : Date,
+});
+
+//Export function to create "SomeModel" model class
+module.exports = mongoose.model('SomeModel', SomeModelSchema );
+ +

You can then require and use the model immediately in other files. Below we show how you might use it to get all instances of the model.

+ +
//Create a SomeModel model just by requiring the module
+var SomeModel = require('../models/somemodel')
+
+// Use the SomeModel object (model) to find all SomeModel records
+SomeModel.find(callback_function);
+ +

Setting up the MongoDB database

+ +

Now that we understand something of what Mongoose can do and how we want to design our models, it's time to start work on the LocalLibrary website. The very first thing we want to do is set up a MongoDb database that we can use to store our library data.

+ +

For this tutorial, we're going to use the MongoDB Atlas free cloud-hosted sandbox database. This database tier is not considered suitable for production websites because it has no redundancy, but it is great for development and prototyping. We're using it here because it is free and easy to set up, and because MongoDB Atlas is a popular database as a service vendor that you might reasonably choose for your production database (other popular choices at the time of writing include Compose, ScaleGrid and ObjectRocket).

+ +
+

Note: If you prefer you can set up a MongoDb database locally by downloading and installing the appropriate binaries for your system. The rest of the instructions in this article would be similar, except for the database URL you would specify when connecting. Note, however, that the Express Tutorial Part 7: Deploying to Production tutorial requires some form of remote database, since the free tier of the Heroku service does not provide persistent storage. It is therefore highly recommended to use MongoDB Atlas.

+
+ +

You will first need to create an account with MongoDB Atlas (this is free, and just requires that you enter basic contact details and acknowledge their terms of service). 

+ +

After logging in, you'll be taken to the home screen:

+ +
    +
  1. Click Build a Cluster button in the Clusters Overview section.
    + Create a cluster on MongoDB Atlas.
  2. +
  3. This will open the Create New Cluster screen.
    + Choose a cloud provider when using MongoDB Atlas. +
      +
    • Select any provider from the Cloud Provider & Region section. Different providers offer different regions.
    • +
    • Select any region marked "FREE TIER AVAILABLE".
    • +
    • Click the Create Cluster button (creation of the cluster will take some minutes).
    • +
    +
  4. +
  5. +

    You will return to the Cluster Overview screen.
    + Setup a collection on MongoDB Atlas.

    + +
      +
    • +

      Click the Collections button.

      +
    • +
    +
  6. +
  7. This will open the Collections section.
    + Create a database on MongoDB Atlas. +
      +
    • Click the Add My Own Data button.
    • +
    +
  8. +
  9. This will open the Create Database screen.
    + Details during database creation on MongoDB Atlas. +
      +
    • Enter the name for the new database as local_library.
    • +
    • Enter the name of the collection as Collection0.
    • +
    • Click the Create button to create the database.
    • +
    +
  10. +
  11. You will return to the Collection screen with your database created.
    + Database creation confirmation on MongoDB Atlas. +
      +
    • Click the Overview tab to return the cluster overview.
    • +
    +
  12. +
  13. From the Cluster0 Overview screen click the Connect button.
    + Configure a connection when after setting up a cluster in MongoDB Atlas.
  14. +
  15. This will open the Connect to Cluster screen.
    + Setup a connection when using MongoDB Atlas. +
      +
    • Click the Add a Different IP Address button, enter 0.0.0.0/0 for the IP Address and click Add IP Address button. +
      +

      Note: It is a best practice to limit the IP addresses that can connect to your database and other resources. Here we allow a connection from anywhere because we don't know where the request will come from after deployment.

      +
      +
    • +
    • Enter a username and password and click Create MongoDB User button. +
      +

      Note: Avoid using special characters in your MongoDB user password as mongoose may not parse the connection string properly.

      +
      +
    • +
    • If you have completed the 2 previous steps, the button Choose a connection method will turn green.
    • +
    • Click the Choose a connection method button.
    • +
    +
  16. +
  17. You should now be able to access the Choose a connection method tab.
    + Choose a connection type when connecting with MongoDB Atlas. +
      +
    • Click the Connect Your Application option.
    • +
    +
  18. +
  19. This will open the Connect screen.
    + Choose the Short SRV connection when settinup a connection on MongoDB Atalas. +
      +
    • Click the Copy button to copy the connection string.
    • +
    • Save this string somewhere safe.
    • +
    • Update the password with your users password.
    • +
    • Replace test with local_library.
    • +
    +
  20. +
+ +

You have now created the database, and have a URL (with username and password) that can be used to access it. This will look something like: mongodb+srv://your_user_name:your_password@cluster0-mbdj7.mongodb.net/local_library?retryWrites=true

+ +

Install Mongoose

+ +

Open a command prompt and navigate to the directory where you created your skeleton Local Library website. Enter the following command to install Mongoose (and its dependencies) and add it to your package.json file, unless you have already done so when reading the Mongoose Primer above.

+ +
npm install mongoose
+
+ +

Connect to MongoDB

+ +

Open /app.js (in the root of your project) and copy the following text below where you declare the Express application object (after the line var app = express();). Replace the database url string ('insert_your_database_url_here') with the location URL representing your own database (i.e. using the information from mongoDB Atlas).

+ +
//Set up mongoose connection
+var mongoose = require('mongoose');
+var mongoDB = 'insert_your_database_url_here';
+mongoose.connect(mongoDB, { useNewUrlParser: true });
+var db = mongoose.connection;
+db.on('error', console.error.bind(console, 'MongoDB connection error:'));
+ +

As discussed in the Mongoose primer above, this code creates the default connection to the database and binds to the error event (so that errors will be printed to the console). 

+ +

Defining the LocalLibrary Schema

+ +

We will define a separate module for each model, as discussed above. Start by creating a folder for our models in the project root (/models) and then create separate files for each of the models:

+ +
/express-locallibrary-tutorial  //the project root
+  /models
+    author.js
+    book.js
+    bookinstance.js
+    genre.js
+
+ +

Author model

+ +

Copy the Author schema code shown below and paste it into your ./models/author.js file. The schema defines an author as having String SchemaTypes for the first and family names (required, with a maximum of 100 characters), and Date fields for the dates of birth and death.

+ +
var mongoose = require('mongoose');
+
+var Schema = mongoose.Schema;
+
+var AuthorSchema = new Schema(
+  {
+    first_name: {type: String, required: true, max: 100},
+    family_name: {type: String, required: true, max: 100},
+    date_of_birth: {type: Date},
+    date_of_death: {type: Date},
+  }
+);
+
+// Virtual for author's full name
+AuthorSchema
+.virtual('name')
+.get(function () {
+
+// To avoid errors in cases where an author does not have either a family name or first name
+// We want to make sure we handle the exception by returning an empty string for that case
+
+  var fullname = '';
+  if (this.first_name && this.family_name) {
+    fullname = this.family_name + ', ' + this.first_name
+  }
+  if (!this.first_name || !this.family_name) {
+    fullname = '';
+  }
+
+  return fullname;
+});
+
+// Virtual for author's lifespan
+AuthorSchema
+.virtual('lifespan')
+.get(function () {
+  return (this.date_of_death.getYear() - this.date_of_birth.getYear()).toString();
+});
+
+// Virtual for author's URL
+AuthorSchema
+.virtual('url')
+.get(function () {
+  return '/catalog/author/' + this._id;
+});
+
+//Export model
+module.exports = mongoose.model('Author', AuthorSchema);
+
+
+ +

We've also declared a virtual for the AuthorSchema named "url" that returns the absolute URL required to get a particular instance of the model — we'll use the property in our templates whenever we need to get a link to a particular author.

+ +
+

Note: Declaring our URLs as a virtual in the schema is a good idea because then the URL for an item only ever needs to be changed in one place.
+ At this point, a link using this URL wouldn't work, because we haven't got any routes handling code for individual model instances. We'll set those up in a later article!

+
+ +

At the end of the module, we export the model.

+ +

Book model

+ +

Copy the Book schema code shown below and paste it into your ./models/book.js file. Most of this is similar to the author model — we've declared a schema with a number of string fields and a virtual for getting the URL of specific book records, and we've exported the model.

+ +
var mongoose = require('mongoose');
+
+var Schema = mongoose.Schema;
+
+var BookSchema = new Schema(
+  {
+    title: {type: String, required: true},
+    author: {type: Schema.Types.ObjectId, ref: 'Author', required: true},
+    summary: {type: String, required: true},
+    isbn: {type: String, required: true},
+    genre: [{type: Schema.Types.ObjectId, ref: 'Genre'}]
+  }
+);
+
+// Virtual for book's URL
+BookSchema
+.virtual('url')
+.get(function () {
+  return '/catalog/book/' + this._id;
+});
+
+//Export model
+module.exports = mongoose.model('Book', BookSchema);
+
+ +

The main difference here is that we've created two references to other models:

+ + + +

BookInstance model

+ +

Finally, copy the BookInstance schema code shown below and paste it into your ./models/bookinstance.js file. The BookInstance represents a specific copy of a book that someone might borrow and includes information about whether the copy is available, on what date it is expected back, and "imprint" (or version) details.

+ +
var mongoose = require('mongoose');
+
+var Schema = mongoose.Schema;
+
+var BookInstanceSchema = new Schema(
+  {
+    book: { type: Schema.Types.ObjectId, ref: 'Book', required: true }, //reference to the associated book
+    imprint: {type: String, required: true},
+    status: {type: String, required: true, enum: ['Available', 'Maintenance', 'Loaned', 'Reserved'], default: 'Maintenance'},
+    due_back: {type: Date, default: Date.now}
+  }
+);
+
+// Virtual for bookinstance's URL
+BookInstanceSchema
+.virtual('url')
+.get(function () {
+  return '/catalog/bookinstance/' + this._id;
+});
+
+//Export model
+module.exports = mongoose.model('BookInstance', BookInstanceSchema);
+ +

The new things we show here are the field options:

+ + + +

Everything else should be familiar from our previous schema.

+ +

Genre model - challenge!

+ +

Open your ./models/genre.js file and create a schema for storing genres (the category of book, e.g. whether it is fiction or non-fiction, romance or military history, etc).

+ +

The definition will be very similar to the other models:

+ + + +

Testing — create some items

+ +

That's it. We now have all models for the site set up!

+ +

In order to test the models (and to create some example books and other items that we can use in our next articles) we'll now run an independent script to create items of each type:

+ +
    +
  1. Download (or otherwise create) the file populatedb.js inside your express-locallibrary-tutorial directory (in the same level as package.json). + +
    +

    Note: You don't need to know how populatedb.js works; it just adds sample data into the database.

    +
    +
  2. +
  3. Enter the following commands in the project root to install the async module that is required by the script (we'll discuss this in later tutorials, ) +
    npm install async
    +
  4. +
  5. Run the script using node in your command prompt, passing in the URL of your MongoDB database (the same one you replaced the insert_your_database_url_here placeholder with, inside app.js earlier): Be sure to pass it  as  a string by wrapping it with ''. +
    node populatedb <your mongodb url>​​​​
    +
  6. +
  7. +
    +

    Note for Windows operating system users: If the above command results in the error DeprecationWarning: current URL string parser is deprecated, change the mongoose.connect(mongoDB); line in populatedb.js file with mongoose.connect(mongoDB, { useNewUrlParser:true });

    + +

    Also, if you encounter problem with your MongoDb connection(e.g. MongoDb connection error: TypeError: Cannot read property 'split' of null) you should try the command above, only WITHOUT wrapping mongodb url as a string with ' ';

    +
    +
  8. +
  9. The script should run through to completion, displaying items as it creates them in the terminal.
  10. +
+ +
+

Tip: Go to your database on mongoDB Atlas (in the Collections tab). You should now be able to drill down into individual collections of Books, Authors, Genres and BookInstances, and check out individual documents.

+
+ +

Summary

+ +

In this article, we've learned a bit about databases and ORMs on Node/Express, and a lot about how Mongoose schema and models are defined. We then used this information to design and implement Book, BookInstance, Author and Genre models for the LocalLibrary website.

+ +

Last of all, we tested our models by creating a number of instances (using a standalone script). In the next article we'll look at creating some pages to display these objects.

+ +

See also

+ + + +

{{PreviousMenuNext("Learn/Server-side/Express_Nodejs/skeleton_website", "Learn/Server-side/Express_Nodejs/routes", "Learn/Server-side/Express_Nodejs")}}

+ +

In this module

+ + diff --git a/files/de/learn/server-side/index.html b/files/de/learn/server-side/index.html new file mode 100644 index 0000000000..49ab06f262 --- /dev/null +++ b/files/de/learn/server-side/index.html @@ -0,0 +1,59 @@ +--- +title: Serverseitige Webseitenprogrammierung +slug: Learn/Server-side +tags: + - Anfänger + - Beginner + - CodingScripting + - Intro + - Landing + - Learn + - Server + - Server-side programming + - Topic + - serverseitiges Programmieren +translation_of: Learn/Server-side +--- +
{{LearnSidebar}}
+ +

Der Themenbereich Dynamische Webseiten Serverseitige Programmierung beinhaltet eine Reihe von Modulen, die erläutern, wie man dynamische Webseiten erstellt. Dynamische Webseiten sind Seiten, die individualisierte Inhalte als Antwort auf HTTP-Anfragen ausliefern. Die Module bieten eine allgemeine Einführung in die serverseitige Programmierung, wie auch spezifische Anfänger-Leitfäden zur Benutzung der Django (Python) und Express (Node.js/JavaScript) Web-Frameworks zum Erstellen von einfachen Anwendungen.

+ +

Die meisten großen Webseiten nutzten irgendeine Art serverseitiger Technologie zur dynamischen Anzeige von verschiedenen Daten, je nach Bedarf. Stellen Sie sich zum Beispiel einmal vor, wie viele Produkte es auf Amazon gibt und wie viele Posts auf Facebook geschrieben wurden. All diese darzustellen, indem man komplett statische Seiten nutzt, wäre völlig ineffizient. Deshalb laden solche Seiten stattdessen erst statische Vorlagen (erstellt mit HTML, CSS und JavaScript), dann aktualisieren sie die Daten in diesen Vorlagen dynamisch, wenn sie benötigt werden, z.B. wenn Sie sich ein anderes Produkt auf Amazon ansehen wollen.

+ +

In der modernen Welt der Webentwicklung ist es sehr empfehlenswert, etwas über serverseitige Entwicklung zu lernen.

+ +

Ihr Lernweg

+ +

Mit dem serverseitigen Programmieren zu beginnen, ist in der Regel leichter als mit der clientseitigen, weil dynamische Webseiten dazu neigen, viele ähnliche Arbeitsabläufe auszuführen (Daten aus einer Datenbank laden und auf der Webseite darstellen, Benutzereingaben validieren und in einer Datenbank speichern, Berechtigungen von Nutzern prüfen und einloggen von Benutzern, etc.) und mit Web-Frameworks konstruiert werden, die diese und andere häufige Webserver-Aufgaben erleichtern.

+ +

Grundlegende Kenntnisse von Konzepten der Programmierung (oder einer bestimmten Programmiersprache) sind hilfreich, aber nicht unbedingt notwendig. Genauso sind Kenntnisse in der clientseitigen Programmierung keine Vorraussetzung, aber ein grundlegendes Verständnis wird Ihnen helfen, besser mit den Entwicklern zusammen zu arbeiten, die Ihre Webseite clientseitig im "Front-end" entwickeln.

+ +

Sie werden verstehen müssen, "wie das Internet funktioniert". Wir empfehlen, dass Sie zuerst die folgenden Themen lesen:

+ + + +

Mit diesem grundlegenden Verständnis sind Sie bereit, sich durch die Module in diesem Abschnitt zu arbeiten. 

+ +

Module

+ +

Dieses Thema enthält die folgenden Module. Sie sollten mit dem ersten Modul beginnen, dann eines der nachfolgenden Module auswählen, die Ihnen zeigen, wie man mit zwei sehr verbreiteten serverseitigen Sprachen arbeitet, indem man das entsprechende Web-Framework verwendet.

+ +
+
Server-side website programming first steps
+
Dieses Modul bietet Server-Technologie-agnostische Informationen über serverseitiges Programmieren von Webseiten, einschließlich der Antworten auf die fundamentalen Fragen des serverseitigen Programmierens — "Was ist es?", "Wie unterscheidet es sich vom clientseitigen Programmieren?" und "Warum ist es so nützlich", einen Überblick über einige der verbreiteteren serverseitigen Web-Frameworks und einen Ratgeber darüber, wie Sie das am besten für Ihre Seite passende auswählen. Zuletzt geben wir noch eine Einführung in die Sicherheit von Webservern.
+
Django Web Framework (Python)
+
Django ist ein extrem beliebtes und vollwertiges Web-Framework, geschrieben in Python. Das Modul erklärt, warum Django so ein gutes Server-Framework ist, wie man eine Entwicklnugsumgebung einrichtet und wie man häufige Aufgaben damit erledigt.
+
Express Web Framework (Node.js/JavaScript)
+
Express ist ein beliebtes Web-Framework, geschrieben in JavaScript und gehostet in der node.js Laufzeitumgebung. Das Modul erklärt einige der Hauptvorteile dieses Frameworks, wie Sie Ihre Entwicklungsumgebung einrichten und wie man damit häufige Entwicklungs- und Bereitstellungsaufgaben umsetzt.
+
+ +

Siehe auch

+ +
+
Node server without framework
+
Dieser Artikel liefert einen einfachen statischen Dateiserver, der mit Node.js erstellt wurde, für diejenigen, die das Framework nicht verwenden möchten.
+
-- cgit v1.2.3-54-g00ecf