iT邦幫忙

DAY 22
0

Node.js 學習筆記系列 第 22

Node.js學習筆記 21:將資料寫入MongoDB

上一篇建立了新增用戶頁面,今天要將從頁面讀到的資料寫入MongoDB裡面。

打開"/routes/index.js",加入以下程式:

/* POST to Add User Service */
router.post('/adduser', function(req, res) {

    // Set our internal DB variable
    var db = req.db;

    // Get our form values. These rely on the "name" attributes
    var userName = req.body.username;
    var Email = req.body.email;

    // Set our collection
    var collection = db.get('usercollection');

    // Submit to the DB
    collection.insert({
        "username" : userName,
        "email" : Email
    }, function (err, doc) {
        if (err) {
            // If it failed, return error
            res.send("There was a problem adding the information to the database.");
        }
        else {
            // If it worked, set the header so the address bar doesn't still say /adduser
            res.location("userlist");
            // And forward to success page
            res.redirect("userlist");
        }
    });
});





這部分的程式有兩個重點。第一個是取得form的資料,請看以下兩行:





    var userName = req.body.username;
    var Email = req.body.email;

Form資料的所在位置是"req.body.NAME","NAME"是指HTML中的"name"屬性(attribute)。例如,這裡"req.body.username"對應"name=username"的那個"input"。

第二個重點是將資料寫入MongoDB。取得"colletion"的方法,我們之前講過。寫入資料只要用"collection"的"insert"方法(method)。可以看到"insert"接受兩個參數,前者為寫入的資料;後者為處理錯誤的callback function。

寫入資料的格式依然是JSON,冒號前後分別代表資料庫的欄位(用雙號號表示)與其相應值。

至於錯誤處理也相當直觀,要提醒的是,沒有錯誤的話,這裡會將頁面轉到"userlist",顯示結果。跳轉分兩步,先設定"location",再執行"redirect"。

[image credit: LUIGI MORANTE]


上一篇
Node.js學習筆記二十:新增用戶頁面
下一篇
Node.js學習筆記 22:全站完成!What's Next?
系列文
Node.js 學習筆記30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言