Exploring and Thinking

Node.js 使用網頁更新MongoDB資料

需要安裝下列 module:
npm install express
npm install mongodb
npm install --save body-parser

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
var express = require('express');

var MongoClient = require('mongodb').MongoClient
    , format = require('util').format;    

/*
 * body-parser is a piece of express middleware that 
 *   reads a form's input and stores it as a javascript
 *   object accessible through `req.body` 
 *
 * 'body-parser' must be installed (via `npm install --save body-parser`)
 * For more info see: https://github.com/expressjs/body-parser
 */
var bodyParser = require('body-parser');

// create our app
var app = express();

// instruct the app to use the `bodyParser()` middleware for all routes

//app.use(bodyParser()); // 原寫法會有錯誤訊息,改以下面寫法:
//------------------------------
app.use(bodyParser.urlencoded({
  extended: true
}));

app.use(bodyParser.json())
//------------------------------

// A browser's default method is 'GET', so this
// is the route that express uses when we visit
// our site initially.
app.get('/', function(req, res){
  // The form's action is '/' and its method is 'POST',
  // so the `app.post('/', ...` route will receive the
  // result of our form
  var html = '<form action="/" method="post">' +
               '身份證號:' +
               '<input type="text" name="uid" placeholder="A123456789" />' +
               '<br>' +
               '到期日:' +
               '<input type="text" name="afterDate" placeholder="2014/01/01" />' +
               '<br>' +
               '<button type="submit">送出</button>' +
            '</form>';
               
  res.send(html);
});

// This route receives the posted form.
// As explained above, usage of 'body-parser' means
// that `req.body` will be filled in with the form elements
app.post('/', function(req, res){
  var uid = req.body.uid;
  var afterDate = req.body.afterDate;

  if (uid != '' & afterDate != '') {
    console.log(uid.toUpperCase()); // 加.toUpperCase()強制大寫
    console.log(afterDate);

    MongoClient.connect('mongodb://10.0.1.1:27017/mydb', function(err, db) {
    if(err) throw err;

    db.collection('mycollection').update({name: uid.toUpperCase()}, {$set: {"data1.after": afterDate, "data2.after": afterDate}}, function(err) {
        if (err) console.warn(err.message);
        else console.log('successfully updated');
        db.close();
      });

    });
  };  

  var html = '送出資料如下<br> <br>' + 
             '身分證號: ' + uid.toUpperCase() + '<br>' +
             '到期日: ' + afterDate + '<br>' +
             '<a href="/">回上頁</a>';
  res.send(html);
});

app.listen(80);

在terminal執行這個js程式即可。(80port在mac需要使用sudo才能跑)

畫面:

參考資料:example reading form input with express 4.0 and body parser for node js
Share:

熱門文章