Docs Menu
Docs Home
/ /

MongoDBとAngularの統合

このガイドでは、 MEANスタックを使用するAngular Webアプリケーションを作成する方法を学習できます。 MEANスタックは、 MongoDB、 Express、 Angular、 Node.jsを使用する Web 開発フレームワークであり、次のレイヤーで構成されています。

  • データベースレイヤー: MongoDB は、データのストレージと検索を提供します。

  • アプリケーション階層: Expressとノード.js は、サーバー側ロジックの中間階層を構成します。

  • プレゼンテーションレイヤー: ユーザー インターフェイスとAngularエンド インタラクションを実装します。

Angular は、動的 Web アプリケーションの作成に使用される TypeScriptフレームワークです。一連のアプリケーション機能用の組み込みパッケージを提供し、コンポーネントベースのアーキテクチャにより、アプリケーションの再利用可能性が非常に高くなります。

TypeScript はJavaScriptでビルドされているため、 MEANスタックの各要素はJavaScriptとJSONに基づいています。その結果、これらの要素間の統合は簡単です。 Angularフロントエンドは、 MongoDB がBSON形式、バイナリJSON拡張機能、およびExpressで直接保存できるJSONドキュメントを作成し、 JavaScript を使用する最小限のフレームワークを提供します。 MongoDB は、 BSONドキュメント向けの高度なインデックス作成とクエリ機能を提供し、ネイティブNode.jsドライバーを備えているため、 JavaScriptアプリケーションに最適なデータ ストアになります。

このチュートリアルでは、 MEANスタックを使用して Webアプリケーションを構築する方法を説明します。アプリケーションはサンプルレストラン データにアクセスし、データをクエリし、その結果をローカルでホストされているサイトに表示します。このチュートリアルには、 MongoDB AtlasでホストされているMongoDBクラスターに接続し、データベースのデータにアクセスして表示する手順も含まれています。

Tip

AngularなしでNode.jsドライバーを使用してMongoDBに接続する場合は、 「 Node.jsドライバーを使い始める 」ガイドを参照してください。

このセクションの手順に従って、プロジェクトの依存関係のインストール、Atlas クラスターの作成、アプリケーションディレクトリの設定を行います。

1

クイック スタートアプリケーションを作成するには、開発環境に次のソフトウェアをインストールします。

前提条件
ノート

最新の LTS または 最新リリース バージョンのいずれかをダウンロードする。

ターミナルで npm install -g @angular/cliを実行中、グローバルにインストールします。

コードエディター

お好みのエディターを使用してください。

ターミナルアプリとシェル

MacOS ユーザーの場合は、 ターミナル または 類似アプリを使用します。Windowsユーザーの場合は、 PowerShell を使用します。

2

MongoDB Atlas は、 MongoDB配置をホストするフルマネージドクラウドデータベースサービスです。 MongoDBデプロイがない場合は、 MongoDBを使い始める チュートリアルを完了することで、 MongoDBクラスターを無料で作成できます。 MongoDBを使い始めるsample_restaurants チュートリアルでは、このチュートリアルで使用される データベースなど、サンプルデータセット をクラスターにロードする方法も説明します。

MongoDBクラスターに接続するには、接続 URI を使用する必要があります。接続文字列を検索する方法については、MongoDBを使い始めるチュートリアルの接続文字列の追加セクションを参照してください。

重要

接続stringを安全な場所に保存します。

3

ターミナルで次のコマンドを実行して、angular-quickstart という名前のプロジェクトのディレクトリを作成します。

mkdir angular-quickstart
cd angular-quickstart

次に、angular-quickstartディレクトリから次のコマンドを実行して server という名前のバックエンド用のフォルダーを作成し、package.jsonファイルを初期化します。

mkdir server
cd server
npm init -y
4

angular-quickstart/serverディレクトリ内の package.jsonファイルに移動します。再利用するためにJavaScriptコードをパッケージ化するための標準形式であるECMAScript モジュールを使用するには、"type"フィールドを指定する既存の行を次の行に置き換えます。

"type": "module",
5

次のコマンドを実行して、mongodbexpresscorsdotenv の依存関係をインストールします。

npm install mongodb express cors dotenv

このコマンドは、 MongoDB、 Expressウェブフレームワーク、クロスオリジンリソース共有用の cors Node.jsパッケージ、 環境変数をロードするための Dotenv をインストールします。

次に、次のコマンドを実行して、TypeScript と必要な型定義をインストールします。

npm install typescript @types/node @types/express tsx

このコマンドは、 TypeScript 、 Node.jsおよびExpressのタイプ定義、および TypeScript ファイルを直接実行中ためのツールである tsx をインストールします。

プロジェクト構造と依存関係を設定したら、このセクションの手順に従ってサーバーを構成し、MongoDBに接続します。

1

angular-quickstart/serverディレクトリに server.ts という名前のファイルを作成し、次のコードを貼り付けます。

Angular-quickstart/サーバー/サーバー.ts
import express from "express";
import cors from "cors";
import restaurants from "./routes/restaurant.js";
const PORT = process.env.PORT || 5050;
const app = express();
app.use(cors());
app.use(express.json());
app.use("/restaurant", restaurants);
// start the Express server
app.listen(PORT, () => {
console.log(`Server listening on port ${PORT}`);
});
2

serverディレクトリで、.envファイルを作成し、次のコードを貼り付けます。

MONGODB_URI=<connection string>
PORT=5050

<connection string>プレースホルダーを、前の手順で保存した接続文字列に置き換えます。

3

serverディレクトリに、db という名前のサブディレクトリを作成します。 connection.ts という名前の新しいファイルをこのサブディレクトリに追加し、次のコードを貼り付けます。

Angular-quickstart/ サーバー/db/ connection.ts
import "dotenv/config";
import { MongoClient, Db } from "mongodb";
const uri = process.env.MONGODB_URI || "";
const client = new MongoClient(uri);
try {
// Connects the client to the server
await client.connect();
// Sends a ping to confirm a successful connection
await client.db("admin").command({ ping: 1 });
console.log(
"Pinged your deployment. You successfully connected to MongoDB!"
);
} catch(err) {
console.error(err);
}
const db: Db = client.db("sample_restaurants");
export default db;

このファイルはMongoDBデプロイに接続し、sample_restaurantsデータベースにアクセスして、データベース接続をテストします。

4

serverディレクトリに、routes という名前のサブディレクトリを作成します。このサブディレクトリに restaurant.ts という名前のファイルを作成し、次のコードを貼り付けます。

Angular-quickstart/ サーバー/ routes/restaurant.ts
import express, { Request, Response } from "express";
import db from "../db/connection.js";
// Creates an instance of the Express router, used to define our routes
const router = express.Router();
// Gets a list of all the restaurants
router.get("/", async (req: Request, res: Response) => {
let collection = await db.collection("restaurants");
let results = await collection.find({}).toArray();
res.send(results).status(200);
});
// Lists restaurants that match the query filter
router.get("/browse", async (req: Request, res: Response) => {
try {
let collection = await db.collection("restaurants");
let query = {
borough: "Queens",
name: { $regex: "Moon", $options: "i" },
};
let results = await collection.find(query).toArray();
res.send(results).status(200);
} catch (err) {
console.error(err);
res.status(500).send("Error browsing restaurants");
}
});
export default router;

このファイルは、sample_restaurantsデータベース内の restaurantsコレクションにアクセスし、次の GET エンドポイントとなる接続されたデバイスを定義します。

  • /:サンプルコレクションからすべてのレストランを検索します

  • /browse: クエリ条件に一致するレストランを検索します。これにより、名前に "Moon" という単語が含まれるクイーンズのレストランがフィルターされます。

アプリケーションのバックエンドを設定した後、このセクションの手順に従ってAngularを構成し、フロントエンド コンポーネントを追加します。

1

angular-quickstartディレクトリに移動し、次のコマンドを実行して新しいAngularアプリケーションを作成します。

ng new client

このコマンドは、一連の設定質問に応答するように要求します。各質問に対して、次のガイダンスに基づいて適切な応答を選択します。

  • オートコンプリートを有効にしますか: Y または N を入力

  • 疑似使用状況データを共有しますか。: Y または N を入力

  • どのスタイルシート システムを使用しますか。追尾可能 CSS を選択します

  • サーバー側レンダリング(SSR)と静的サイト生成(SSG/プレレンダリング)を有効にしますか。 Y または N を入力

  • Angular のベストプラクティスでどのAIツールを構成しますか。好みのツールを選択します

コマンドの実行中後、プロジェクトにはフロントエンド スキャフォールディングを含む clientディレクトリが作成されます。コマンドは、 UI形式のフレームワークである RailwindCSS を使用するようにプロジェクトを構成します。

2

ゾーン.js をインストールするには、クライアントディレクトリから次のコマンドを実行します。

npm install zone.js

アプリケーションは、変更を追跡し、 UIを自動的に更新するために zone.js ライブラリを使用します。

3

clientディレクトリから、次のコマンドを実行して、バックエンドへのAPI呼び出しを処理するサービスを生成します。

ng generate service restaurant

client/src/app/restaurant.tsファイルに移動し、内容を次のコードで置き換えます。

Angular-quickstart/クライアント/src/ アプリ/restaurant.ts
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';
export interface Restaurant {
_id: string;
name: string;
borough: string;
cuisine: string;
}
@Injectable({
providedIn: 'root'
})
export class RestaurantService {
private apiUrl = 'http://localhost:5050/restaurant';
constructor(private http: HttpClient) {}
getAllRestaurants(): Observable<Restaurant[]> {
return this.http.get<Restaurant[]>(this.apiUrl);
}
getFilteredRestaurants(): Observable<Restaurant[]> {
return this.http.get<Restaurant[]>(`${this.apiUrl}/browse`);
}
}

このサービスは、 Express APIからレストランのデータを取得するためのメソッドを定義します。

4

client/src/app/app.routes.tsファイルに移動し、内容を次のコードで置き換えます。

Angular-quickstart/クライアント/src/ アプリ/ アプリ. route.ts
import { Routes } from '@angular/router';
import { RestaurantListComponent } from './restaurant-list/restaurant-list';
export const routes: Routes = [
{ path: '', component: RestaurantListComponent },
{ path: 'browse', component: RestaurantListComponent }
];

このファイルは、クライアント側ルーティングを構成し、次のルートを定義します。

  • /: /restaurant/ APIエンドポイントからのすべてのレストランを表示

  • /browse: /restaurant/browse APIエンドポイントからフィルタリングされたレストランを表示

5

client/src/app/app.config.tsファイルに移動し、内容を次のコードで置き換えます。

Angular-quickstart/クライアント/src/ アプリ/ アプリ.config.ts
import { ApplicationConfig, provideZoneChangeDetection } from '@angular/core';
import { provideRouter } from '@angular/router';
import { provideHttpClient } from '@angular/common/http';
import { routes } from './app.routes';
export const appConfig: ApplicationConfig = {
providers: [
provideZoneChangeDetection({ eventCoalescing: true }),
provideRouter(routes),
provideHttpClient()
]
};

この構成により、 APIリクエストを行うためのHTTPクライアント機能が有効になります。

6

clientディレクトリから次のコマンドを実行して、レストランを表示するためのコンポーネントを生成します。

ng generate component restaurant-list

client/src/app/restaurant-list/restaurant-list.tsファイルに移動し、内容を次のコードで置き換えます。

Angular-quickstart/クライアント/src/ アプリ/restaurant-list/restaurant-list.ts
import { Component, OnInit } from '@angular/core';
import { CommonModule } from '@angular/common';
import { Router } from '@angular/router';
import { RestaurantService, Restaurant } from '../restaurant';
@Component({
selector: 'app-restaurant-list',
standalone: true,
imports: [CommonModule],
templateUrl: './restaurant-list.html',
styleUrl: './restaurant-list.css'
})
export class RestaurantListComponent implements OnInit {
restaurants: Restaurant[] = [];
loading = true;
error = '';
constructor(
private restaurantService: RestaurantService,
public router: Router
) {}
ngOnInit(): void {
this.loadRestaurants();
}
loadRestaurants(): void {
const isFiltered = this.router.url === '/browse';
const observable = isFiltered
? this.restaurantService.getFilteredRestaurants()
: this.restaurantService.getAllRestaurants();
observable.subscribe({
next: (data) => {
this.restaurants = data;
this.loading = false;
},
error: (err) => {
this.error = 'Failed to load restaurants';
this.loading = false;
console.error('Error loading restaurants:', err);
}
});
}
}

次に、client/src/app/restaurant-list/restaurant-list.htmlファイルに移動し、内容を次のコードで置き換えます。

Angular-quickstart/クライアント/src/ アプリ/restaurant-list/restaurant-list.html
<div *ngIf="loading" class="text-center py-8">
<p class="text-gray-600">Loading restaurants...</p>
</div>
<div *ngIf="error" class="bg-red-100 border border-red-400 text-red-700 px-4 py-3 rounded">
{{ error }}
</div>
<div *ngIf="!loading && !error">
<h3 class="text-lg font-semibold p-4">
{{ router.url === '/browse' ? 'Filtered Restaurants (Queens, containing "Moon")' : 'All Restaurants' }}
</h3>
<div class="border rounded-lg overflow-hidden">
<div class="relative w-full overflow-auto">
<table class="w-full caption-bottom text-sm">
<thead class="[&_tr]:border-b">
<tr class="border-b transition-colors hover:bg-muted/50 data-[state=selected]:bg-muted">
<th class="h-12 px-4 text-left align-middle font-medium text-muted-foreground [&:has([role=checkbox])]:pr-0">
Name
</th>
<th class="h-12 px-4 text-left align-middle font-medium text-muted-foreground [&:has([role=checkbox])]:pr-0">
Borough
</th>
<th class="h-12 px-4 text-left align-middle font-medium text-muted-foreground [&:has([role=checkbox])]:pr-0">
Cuisine
</th>
</tr>
</thead>
<tbody class="[&_tr:last-child]:border-0">
<tr *ngFor="let restaurant of restaurants" class="border-b transition-colors hover:bg-muted/50 data-[state=selected]:bg-muted">
<td class="p-4 align-middle [&:has([role=checkbox])]:pr-0">
{{ restaurant.name }}
</td>
<td class="p-4 align-middle [&:has([role=checkbox])]:pr-0">
{{ restaurant.borough }}
</td>
<td class="p-4 align-middle [&:has([role=checkbox])]:pr-0">
{{ restaurant.cuisine }}
</td>
</tr>
</tbody>
</table>
</div>
</div>
</div>

このコンポーネントは、現在のルートに基づいてレストラン情報を検索して表示します。

7

client/src/app/app.tsファイルに移動し、内容を次のコードで置き換えます。

Angular-quickstart/クライアント/src/ アプリ/ アプリ.ts
import { Component } from '@angular/core';
import { RouterOutlet, RouterLink, RouterLinkActive } from '@angular/router';
@Component({
selector: 'app-root',
standalone: true,
imports: [RouterOutlet, RouterLink, RouterLinkActive],
templateUrl: './app.html',
styleUrl: './app.css'
})
export class AppComponent {
title = 'Restaurant Browser';
}

次に、client/src/app/app.htmlファイルに移動し、内容を次のコードで置き換えます。

angular-quickstart/client/src/app/app.html
<div class="w-full p-6">
<nav class="flex justify-between items-center mb-6">
<a routerLink="/">
<img
alt="MongoDB logo"
class="h-10 inline"
src="https://d3cy9zhslanhfa.cloudfront.net/media/3800C044-6298-4575-A05D5C6B7623EE37/4B45D0EC-3482-4759-82DA37D8EA07D229/webimage-8A27671A-8A53-45DC-89D7BF8537F15A0D.png"
/>
</a>
<div class="flex gap-4">
<a routerLink="/" routerLinkActive="font-bold" [routerLinkActiveOptions]="{exact: true}" class="text-blue-600 hover:underline">
All Restaurants
</a>
<a routerLink="/browse" routerLinkActive="font-bold" class="text-blue-600 hover:underline">
Filtered Restaurants
</a>
</div>
</nav>
<router-outlet></router-outlet>
</div>

これは、ナビゲーションを含み、現在のルートに基づいて適切な子コンポーネントをレンダリングするメインのアプリケーションコンポーネントです。

8

client/src/main.tsファイルに移動し、内容を次のコードで置き換えます。

Angular-quickstart/クライアント/src/main.ts
import 'zone.js';
import { bootstrapApplication } from '@angular/platform-browser';
import { appConfig } from './app/app.config';
import { AppComponent } from './app/app';
bootstrapApplication(AppComponent, appConfig)
.catch((err) => console.error(err));

このファイルは、アプリケーションへのエントリ点として機能し、構成を適用してレンダリングします。

最後に、このセクションの手順に従ってアプリケーションを実行し、レンダリングされたレストラン データを表示します。

1

serverディレクトリから、次のコマンドを実行してサーバーを起動します。

npx tsx server.ts

成功させた場合、このコマンドは次の情報を出力します。

Pinged your deployment. You successfully connected to MongoDB!
Server listening on port 5050
2

別のターミナルウィンドウで、clientディレクトリに移動します。次のコマンドを実行して、 Angularフロントエンドを起動します。

ng serve

成功させた場合、このコマンドは次の情報を出力します。

Application bundle generation complete.
Watch mode enabled. Watching for file changes...
NOTE: Raw file sizes do not reflect development server per-request transformations.
➜ Local: http://localhost:4200/
➜ press h + enter to show help

Angularアプリケーションは、データを取得するためにポート 4200 からポート 5050 にHTTPリクエストを送信します。

3

http://localhost:4200 / URLを開きます。最初のランディング ページには、sample_restaurants.restaurants コレクション内のすべてのレストランのリストが表示されます。

すべてのレストランを表示するランディング ページ

次に、ナビゲーション バーの Filtered Restaurants リンクをクリックして、nameboroughフィールドクエリに一致するレストランを表示します。

一致するレストランを表示するウェブページ

クイック スタート チュートリアルが完了しました。

これらの手順を完了すると、 MongoDBデプロイに接続し、サンプルレストラン データに対してクエリを実行し、ローカルでホストされているウェブサイトで結果をレンダリングするAngular Webアプリケーションが作成されます。

Angular、 MongoDB、 MEANスタックの詳細については、次のリソースを表示します。

戻る

問題とヘルプ

項目一覧