Meanjs-build-data-model

提供:Dev Guides
移動先:案内検索

MEAN.JS-データモデルの構築

この章では、Node-expressアプリケーションでデータモデルを使用する方法を示します。

MongoDBは、JSON形式でデータを保存するオープンソースのNoSQLデータベースです。 リレーショナルデータベースで使用するテーブルと行を使用する代わりに、ドキュメント指向の_data model_を使用してデータを格納します。 この章では、Mongodbを使用してデータモデルを構築します。

データモデルは、ドキュメントに存在するデータとドキュメントに存在するデータを指定します。 MongoDBをインストールするには、https://docs.mongodb.com/manual/installation/[MongoDBの公式インストール]を参照してください。

前の章のコードを使用します。 次のリンクからソースコードをダウンロードできます:[リンク]。 zipファイルをダウンロードします。システムでそれを抽出します。 ターミナルを開き、以下のコマンドを実行してnpmモジュールの依存関係をインストールします。

$ cd mean-demo
$ npm install

Mongooseをアプリケーションに追加する

Mongooseは、MongoDBを強力にすることでデータの環境と構造を指定するデータモデリングライブラリです。 コマンドラインを使用して、Mongooseをnpmモジュールとしてインストールできます。 ルートフォルダに移動し、以下のコマンドを実行します-

$ npm install --save mongoose

上記のコマンドは、新しいパッケージをダウンロードし、_node_modules_フォルダーにインストールします。 _-- save_フラグは、このパッケージを_package.json_ファイルに追加します。

{
   "name": "mean_tutorial",
   "version": "1.0.0",
   "description": "this is basic tutorial example for MEAN stack",
   "main": "server.js",
   "scripts": {
      "test": "test"
   },
   "keywords": [
      "MEAN",
      "Mongo",
      "Express",
      "Angular",
      "Nodejs"
   ],
   "author": "Manisha",
   "license": "ISC",
   "dependencies": {
      "express": "^4.17.1",
      "mongoose": "^5.5.13"
   }
}

接続ファイルのセットアップ

データモデルを操作するには、_app/models_フォルダーを使用します。 以下のようにモデル_students.js_を作成しましょう-

var mongoose = require('mongoose');

//define our students model
//module.exports allows us to pass this to other files when it is called
module.exports = mongoose.model('Student', {
   name : {type : String, default: ''}
});

接続ファイルを作成するには、ファイルを作成してアプリケーションで使用します。 _config/db.js_に_db.js_というファイルを作成します。 ファイルの内容は次のとおりです-

module.exports = {
   url : 'mongodb://localhost:27017/test'
}

ここで、_test_はデータベース名です。

ここでは、MongoDBがローカルにインストールされていると想定しています。 インストールしたら、Mongoを起動し、名前テストでデータベースを作成します。 このデータベースには、学生という名前のコレクションがあります。 このコレクションにいくつかのデータを挿入します。 この場合、db.students.insertOne(\ {name: 'Manisha'、place: 'Pune'、country: 'India'});を使用してレコードを挿入しました。

_db.js_ファイルをアプリケーション、つまり_server.js_に取り込みます。 ファイルの内容は以下のとおりです-

//modules =================================================
const express = require('express');
const app = express();
var mongoose = require('mongoose');
//set our port
const port = 3000;
//configuration ===========================================

//config files
var db = require('./config/db');
console.log("connecting--",db);
mongoose.connect(db.url);//Mongoose connection created

//frontend routes =========================================================
app.get('/', (req, res) ⇒ res.send('Welcome to finddevguides!'));

//defining route
app.get('/tproute', function (req, res) {
   res.send('This is routing for the application developed using Node and Express...');
});

//sample api route
//grab the student model we just created
var Student = require('./app/models/student');
app.get('/api/students', function(req, res) {
  //use mongoose to get all students in the database
   Student.find(function(err, students) {
     //if there is an error retrieving, send the error.
     //nothing after res.send(err) will execute
      if (err)
         res.send(err);
      res.json(students);//return all students in JSON format
   });
});
//startup our app at http://localhost:3000
app.listen(port, () ⇒ console.log(`Example app listening on port ${port}!`));

次に、以下のコマンドでアプリケーションを実行します-

$ npm start

以下の画像に示すように、確認が得られます-

接続ファイルの設定

ここで、ブラウザに移動して http://localhost:3000/api/students と入力します。 あなたは、以下の画像に示すようにページを取得します-

接続ファイル学生