express+mongoogleは、mongodbの添削操作を実現します。


本論文の実例は、express+mongoogleがmongodbの添削操作を実現することを述べている。皆さんに参考にしてあげます。具体的には以下の通りです。
プロジェクト住所:https://github.com/jrainlau/mongoose_クラウド
冒頭に書く
この文章は主に私がどのようにexpress+mongoogleを使ってmongodbを添削して操作を調べることを実現しますか?cnodeコミュニティのすべての逸品の文章の助けに感謝します。そして@airuiunのオープンソースプロジェクトairuiun/モングースクラウドは私に対する啓発です。
nodejsを勉強してもう半月も経ちました。何かを作ることをずっと考えています。PHPの経験があるので、データベースの操作に興味があります。nodejsを勉強する勢いに乗って、mongodbも一緒に勉強するつもりです。mongodbはMySQLよりも柔軟にしてくれますし、上手になります。ある程度の知識を身につけたら、開発に着手し、基礎的な添削の機能を実現します。
プロジェクトの準備
まず、一定のnodejs、express及びmongodbの知識を身につけて、すでにexpressとmongooseモジュールをインストールしました。mongodbの問題については、私のもう一つの文章を読むことができます。win 7の下で、快速にmongodbを起動する方法。には、詳細なインストールと配置のプロセスがあります。同時にrobomongoをmongodbの可視化操作ツールとして紹介します。直接データベースを見て操作してもいいです。
プロジェクト開始
コマンドラインを開いて、入力します。express -e mongoose_crud「-e」はejsをモデルエンジンとして使うことを表します。プロジェクトファイル構造を作成して実行します。cd mongoose_crud && npm installは、依存パケットをインストールする。
今私達のプロジェクトはこのような長さが必要です。

次の操作を容易にするために、プロジェクトを起動するためにsupervisorを使用することを推奨します。npm install supervisor -g私達のプロジェクトのフォルダに入って、私達はpackage.jsonファイルを書き換えて、中の“scripts”を下の書き方に変えます。

"scripts": {
 "start": "supervisor ./bin/www"
 },
今後プロジェクトを起動するには、プロジェクトフォルダの下でnpm startを実行すればいいです。
ファイルを書き換える
expressは自分で作成したファイルの構造がそんなにきれいではないので、少し修正して、次の仕事に便利です。
まず\routeフォルダを開き、無駄なuser.jsを削除し、index.jsを開き、以下の内容に修正する。

'use strict'
const routes = (app) => {
 app.get('/', (req, res, next) => {
  res.render('index', { title: 'Jrain    '})
 })
}
app.jsフォルダを開いて、以下の内容に変更します。

var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');

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

var app = express();

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');

// uncomment after placing your favicon in /public
app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

routes(app)

// catch 404 and forward to error handler
app.use(function(req, res, next) {
 var err = new Error('Not Found');
 err.status = 404;
 next(err);
});

// error handlers

// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
 app.use(function(err, req, res, next) {
 res.status(err.status || 500);
 res.render('error', {
  message: err.message,
  error: err
 });
 });
}

// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
 res.status(err.status || 500);
 res.render('error', {
 message: err.message,
 error: {}
 });
});

module.exports = app;
実は、ルーティング管理をapp.jsから\routes\index.jsに移転しました。管理に便利です。
私たちはテストしてもいいです。ブラウザでlocalhost:3000を入力して、もし出力が「JRAnは本当にかっこいい」ではないなら、それはあなたのプロジェクトに問題があります。OKです。これからは本格的な開発です。
添削と検索機能の実現
ルートディレクトリの下にmodulesフォルダを新規作成し、my_class.jsというファイルを作成します。私達のこのプロジェクトは1つの学年とクラスの学生の管理システムを創立するので、学生の名前と学号に対して添削して調べる操作を行うことができます。ファイルの内容は以下の通りです。

'use strict'
const mongoose = require('mongoose')
//   mongodb
mongoose.connect('mongodb://localhost/test')
//        
const db = mongoose.connection
db.on('error', console.error.bind(console, '    :'))
db.once('open', (callback) => {
 console.log('MongoDB    !!')
})
//   schema
const classSchema = new mongoose.Schema({
 name: String,
 studentId: Number
})
//   model
const classModel = mongoose.model('newClass', classSchema) // newClass         

module.exports = classModel
各セクションの役割はコメントを見ればいいです。もうプロジェクトをmongodbに接続しました。次のステップを進めます。
私達は5つのページがあります。それぞれトップページです。学生情報はページを増やします。学生はページを削除します。学生はページを直します。学生はページを探します。\viewsフォルダ内に対応するejsファイルを作成すればいいです。コードは貼りません。直接にプロジェクトを見に行くことができます。
https://github.com/jrainlau/mongoose_crud/tree/master/view
その後、\routes\index.jsに戻ります。ほとんどの論理はこの中で行われます。
中の内容を下記のコードに修正します。

'use strict'
const classModel = require('../modules/my_class')
const routes = (app) => {
 //   
 app.get('/', (req, res, next) => {
  let response = res
  classModel.find({}, (err, result, res) => {
   if(err) return console.log(err)
   response.render('index', { result })
  })
 })
 //       
 app.get('/create', (req, res, next) => {
  res.render('create', {})
 })
 app.post('/create', (req, res, next) => {
  let newStudent = [{
   name: req.body.name,
   studentId: req.body.student_id
  }]
  classModel.create(newStudent, (err) => {
   if(err) return console.log(err)
   res.send("<a href='/'>    ,      </a>")
  })
 })
 //       
 app.get('/del', (req, res, next) => {
  let response = res
  classModel.find({}, (err, result, res) => {
   if(err) return console.log(err)
   response.render('del', { result })
  })
 })
 app.post('/del', (req, res, next) => {
  classModel.remove({_id: req.body.student}, (err, result) => {
   if(err) return console.log(err)
   console.log(result.result)
   res.send("<a href='/'>    ,      </a>")
  })
 })
 //       
 app.get('/update', (req, res, next) => {
  let response = res
  classModel.find({}, (err, result, res) => {
   if(err) return console.log(err)
   response.render('update', { result })
  })
 })
 app.post('/update', (req, res, next) => {
  console.log(req.body)
  let num = req.body.num,
   condiction = {_id: req.body._id[num]},
   query = {$set: {name: req.body.name[num], studentId: req.body.student_id[num]}}
  classModel.update(condiction, query, (err, result) => {
   if(err) {
    console.log(err)
    res.send('<script>alert("         ")</script>')
   }
   res.send("<a href='/'>    ,      </a>")
  })
 })
 //     
 app.get('/reach', (req, res, next) => {
  let result = null
  res.render('reach', { result })
 })
 app.post('/reach', (req, res, next) => {
  console.log(req.body)
  let response = res
  let reachType = req.body.reach_type,
   keyWord = req.body.keyword
  if (reachType == 0) {
   classModel.find({name: keyWord}, (err, result) => {
    if(err) return console.log(err)
    response.render('reach', { result })
   })
  } else {
   classModel.find({studentId: keyWord}, (err, result) => {
    if(err) return console.log(err)
    response.render('reach', { result })
   })
  }
 })
}
module.exports = routes
その原理としては、プログラムはpostを通じてパラメータを受信し、対応する操作を行い、添削調査の機能を実現する。主に使用されるAPIは以下のようなものがあります。
  • .find()は、学生情報を読み取り、検索するためのものです。
  • .create()は、学生情報を増やすためのものです。これは、modelの操作に基づいて、必要な追加コンテンツとして、jsonオブジェクトを入力し、具体的には、自分で見ることができます。
  • .update()は、学生情報を更新するためのものです。
  • .remove()は、学生情報を削除するためのものです。
  • 私たちのプロジェクトはもう全部完成しました。テストしてみましょう。
    終わりに
    このものは教程ではなくて、自分で勉強した記録としてだけです。他の人に役に立ったらいいですね。私の話が間違っていると感じたら、教えてください。ありがとうございます
    ここで述べたように、みんなのMongoDBデータベースプログラムの設計に役に立ちます。