iT邦幫忙

2019 iT 邦幫忙鐵人賽

DAY 11
0
Modern Web

三十天全端學習:透過javascript(Onsen UI)、python(tornado)、非關聯式資料庫(mongoDB)完成全端學習,建置web app、mobile app。系列 第 11

三十天全端學習(javascript、python、mongoDB)---第十一天:MongoDB安裝與使用III---使用node.js驅動實作練習

https://ithelp.ithome.com.tw/upload/images/20181019/20102269UWDbDmNakN.jpg

第十一天:MongoDB安裝與使用III---使用node.js驅動實作練習

day11會帶大家著重在實作上,並透過gui軟體Robo 3T來查看資料庫的使用狀況。


前提概要

day9day10簡單的說明了如何與mongoDB網路端與本地端連線的練習。


本文概要

多個node.js控制mongoDB的連線,所有的檔案都會放到github


正文開始

1. 練習0: link mongodb 連接mongoDB

第一個練習,讓大家將day10的link0.js從連接mlab變成連接到本地端。

//day11 練習0: link mongodb

const MongoClient = require('mongodb').MongoClient;
const assert = require('assert');


const url = 'mongodb://localhost:27017';


// 填入你的DB名稱  
const dbName = 'HeartRate';

//main--主程式區
MongoClient.connect(url, function(err, client) {
  assert.equal(null, err);
  
   //注意這一行,最後連線成功,cmd模式會輸出 
  console.log("Connected successfully to server");

  const db = client.db(dbName);

  client.close();
});

將url改為 localhost:27017這是預設的,如果你有更改,請改成自己的。
連線成功,應該會出現 Connected successfully to server的字樣。

2. day11 練習1: link mongodb + insert some documents

//day11 練習1: link mongodb + insert some documents
const MongoClient = require('mongodb').MongoClient;
const assert = require('assert');


// Connection URL---
const url = 'mongodb://localhost:27017';
// Database Name---
const dbName = 'HeartRate';

//2.insertDocuments
const insertDocuments = function(db, callback) {
  // Get the documents collection
  const collection = db.collection('h1f001');
  // Insert some documents  插入你需要的資料。
  collection.insertMany([
    {day9 : 1}, {day10 : 2}, {day11 : 3}
  ], function(err, result) {
    assert.equal(err, null);
    assert.equal(3, result.result.n); //比對結果是否為3筆
    assert.equal(3, result.ops.length);  //比對是否為3筆
    console.log("Inserted "+ result.result.n +" documents into the collection");
    callback(result);
  });
}


//main---主程式區
MongoClient.connect(url, function(err, client) {
  assert.equal(null, err);
  console.log("Connected successfully to server");

  const db = client.db(dbName);
  //operations--
  //Insert some documents
  insertDocuments(db, function() {
    client.close();
  });

});

這邊練習插入資料,以及了解資料的測試驗證,若插入的是四筆資料,請再比對的地方修改為4,否則會跳出錯誤!!

https://ithelp.ithome.com.tw/upload/images/20181019/20102269O1P6kG83CJ.png
插入成功會跳出以上訊息。

https://ithelp.ithome.com.tw/upload/images/20181019/20102269xrCxxGNiCd.png
查看Robo 3T 是否新增了三筆資料。

3.小作業

  1. 若是插入2筆資料或是4筆資料,不改驗證比對的地方,會發生甚麼事情?
  2. 比對練習0跟練習1的主程式。

小結

今天就先帶大家練習更改連接本地端,以及插入資料。


上一篇
三十天全端學習(javascript、python、mongoDB)---第十天:MongoDB安裝與使用II---使用node.js驅動網路端mongoDB(mlab)
下一篇
三十天全端學習(javascript、python、mongoDB)---第十二天:MongoDB安裝與使用IV---使用node.js驅動實作練習
系列文
三十天全端學習:透過javascript(Onsen UI)、python(tornado)、非關聯式資料庫(mongoDB)完成全端學習,建置web app、mobile app。30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言