通过使用Express和MongoDB,快速创建REST API

首先為了自己的筆記,我寫下這篇文章。
從安裝Express和MongoDB,到創建和獲取食譜等,我創建了一個簡單的Web API。到撰寫時為止,我還沒有創建網頁。
在這裡,我使用了Express Application Generator,但如果只是想要創建Web API,也可以考慮從頭開始自己動手做。

完成版本的源代码

    recipes(v1.0.0)

请参考我非常感谢您提供的参考,我将非常好好利用它。

    • Node.js+Express+MongoDBでREST APIをつくる

 

    • MongoDB 3.0.6(Windows版)をインストールして起動するまでの手順

 

    Express Todo Example

本题 tí)

建立Express应用的框架

安装Express应用程序生成器

$ npm install express-generator -g
使用Express Application Generator创建框架

$ cd <適当なディレクトリ>
$ express --view=pug <アプリの名前>
$ cd <アプリの名前>
$ npm install && npm start
请用浏览器确认http://localhost:3000和http://localhost:3000/users都有简洁的界面。

将源代码解释为WebAPI的转换。
在本地主机上的端口3000上,可以看到以下代码(摘录)似乎与表示相关。

var app = express();

app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'pug');

var index = require('./routes/index');

app.use('/', index);
var router = express.Router();

router.get('/', function(req, res, next) {
  res.render('index', { title: 'Express' });
});

module.exports = router
extends layout

block content
  h1= title
  p Welcome to #{title}

根据当前的配置,应用程序使用app.use将根路径和路由器连接起来。
通过router.get来指定对根路径的GET请求的行为。
通过res.render来指定视图以及可以在视图中使用的本地变量。
显示views/index.pug视图。

不再使用res.render,而是使用res.json,这样可以变成返回固定JSON的Web API!

var router = express.Router();

router.get('/', function(req, res, next) {
  res.json({
    recipes: [
      {title: 'nikujaga', content: 'niku + jaga'},
      {title: 'curry', content: 'veggie + curry cube'}
    ]
  });
});

module.exports = router

尝试使用MongoDB.

下载并安装MongoDB社区服务器。安装完成后,请将 C:\Program Files\MongoDB\Server\3.0\bin 路径添加到PATH中(注意可能存在不同版本)。

请确认是否可使用命令。

$ mongod --version
$ mongo --version

mongod :MongoDBサーバ起動用コマンド
mongo :MongoDBシェル起動用のコマンド

MongoDB服务器的启动配置(参考:配置文件选项)在启动MongoDB服务器时,需要指定数据库的数据和日志存储位置。本次我们将尝试在配置文件中进行如下设置。(※请根据需要自行更改路径)

storage:
  dbPath: db\data

systemLog:
  destination: file
  path: db\logs\mongodb.log

storage.dbPath : DBのデータを格納するためのディレクトリ

systemLog.destination : ログを格納する場所として、 file または syslog を指定

systemLog.path : (上記で file を設定した場合)ログを格納するファイル名

启动MongoDB服务器(参考:启动mongod进程)

$ mongod --config db/mongodb.conf
打开MongoDB Shell并进行尝试(参考:mongo Shell快速参考)

$ mongo

可以使用quit()来退出MongoDB shell。

停止 MongoDB 服务器停止MongoDB服务器的方法可以在MongoDB Shell中执行。还有其他停止方法。

(从MongoDB Shell停止mongod进程)

$ mongo
$ use admin
$ db.shutdownServer()

使用Node.js连接MongoDB

安装MongoDB这是一个可以很容易地创建MongoDB模型等的工具。

$ npm install mongoose --save
使用 mongoose 在 MongoDB 上建立连接并创建模型。为了获取和创建数据库的数据,需要定义模式。有关整体的详细说明,请参考 README,有关模式详细定义的方法,请参考 SchemaTypes。

var mongoose = require('mongoose');
var Schema = mongoose.Schema;

var Recipe = new Schema({
    title: String,
    content: String,
    created_at: {
      type: Date,
      default: Date.now
    },
    last_modified_at: {
      type: Date,
      default: Date.now
    }
});

mongoose.model('Recipe', Recipe);
mongoose.connect('mongodb://localhost:27017/recipes');

可以通过在 app.js 的开头添加 require(‘./db/mongo’) 来在应用程序启动时连接到 MongoDB。

使用mongoose进行数据创建和获取。
可以创建一个先前定义的Recipe模式的实例,并且可以进行保存和搜索,
使用save和find函数。

var db = require('mongoose');
var Recipe = db.model('Recipe');

new Recipe({
      title: 'jaga bata',
      content: 'potato + butter'
}).save(function (err, recipe){
  if(err) {
    console.log(err);
  } else {
    console.log('yay');
    console.log(recipe);
  }
});

Recipe.find()
  .exec()
  .then(function(recipes){
    console.log('wow');
    console.log(recipes);
  })
  .catch(function(err) {
    console.log(err);
  });

将Express与MongoDB结合使用
通过Express可以创建GET请求和POST请求,并将其与上述代码组合在一起,从而可以创建动态的Web API。例如,对于前面提到的根路径的GET请求的实现如下所示。

var router = express.Router();

router.get('/', function(req, res, next) {
  Recipe.find()
    .exec()
    .then(function(recipes){
      res.json({recipes: recipes});
    })
    .catch(function(err) {
      res.status(500).json({err: err});
    });
});

module.exports = router

完结感谢您阅读到最后!源代码将逐渐进行改进。

bannerAds