1. 程式人生 > >node.js學習筆記(7)--Node.js與MongoDB簡單互動

node.js學習筆記(7)--Node.js與MongoDB簡單互動

1.建立工程

E:\test>express mongo -e

   create : mongo
   create : mongo/package.json
   create : mongo/app.js
   create : mongo/public
   create : mongo/public/javascripts
   create : mongo/views
   create : mongo/views/index.ejs
   create : mongo/views/error.ejs
   create : mongo/routes
   create : mongo/routes/index.js
   create : mongo/routes/users.js
   create : mongo/public/images
   create : mongo/public/stylesheets
   create : mongo/public/stylesheets/style.css
   create : mongo/bin
   create : mongo/bin/www

   install dependencies:
     > cd mongo && npm install

   run the app:
     > SET DEBUG=mongo:* & npm start


E:\test>

2.安裝MongoDB模組

E:\test>cd mongo

E:\test\mongo>npm install mongodb -save
[email protected] node_modules\mongodb
├── [email protected]
├── [email protected] ([email protected], [email protected], [email protected]
.0.1, [email protected])
└── [email protected] ([email protected]
, [email protected]) E:\test\mongo>
npm install 與 npm install -save的區別是:後者安裝的同時,將資訊寫入package.json中專案路徑中,如果有package.json檔案時,直接使用npm install方法就可以根據dependencies配置安裝所有的依賴包,這樣程式碼提交到github時,就不用提交node_modules這個檔案夾了。


3.連線MongoDB資料庫

修改app.js檔案 我們可以刪除如下程式碼:(當然不刪沒什麼關係)
// 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: {}
  });
});
加上監聽讓我們能通過入口啟動(也就是輸入 node app 不需要輸入 npm start了)
app.listen(3000, function () {
  console.log('app is listening at port 3000');
});
宣告MongoClient
var MongoClient = require('mongodb').MongoClient;
連線mongodb (其中localhost是地址後面跟的是埠以及資料庫名字,請根據自己情況修改)
var url = 'mongodb://localhost:27017/first';
MongoClient.connect(url, function(err, db) {
  console.log("資料庫連線成功");
  db.close();
});
啟動服務(我們現在輸入node app啟動
E:\test\mongo>node app
module.js:340
    throw err;
    ^

Error: Cannot find module 'express'
    at Function.Module._resolveFilename (module.js:338:15)
    at Function.Module._load (module.js:289:25)
    at Module.require (module.js:366:17)
    at require (module.js:385:17)
    at Object.<anonymous> (E:\test\mongo\app.js:1:77)
    at Module._compile (module.js:435:26)
    at Object.Module._extensions..js (module.js:442:10)
    at Module.load (module.js:356:32)
    at Function.Module._load (module.js:313:12)
    at Function.Module.runMain (module.js:467:10)
好吧,報錯了 原來是我們忘記安裝依賴模組了
E:\test\mongo>npm install
[email protected] node_modules\ejs

[email protected] node_modules\debug
└── [email protected]

[email protected] node_modules\serve-favicon
├── [email protected]
├── [email protected]
├── [email protected]
└── [email protected]

[email protected] node_modules\cookie-parser
├── [email protected]
└── [email protected]

[email protected] node_modules\morgan
├── [email protected]
├── [email protected]
├── [email protected]
└── [email protected] ([email protected])

[email protected] node_modules\express
├── [email protected]
├── [email protected]
├── [email protected]
├── [email protected]
├── [email protected]
├── [email protected]
├── [email protected]
├── [email protected]
├── [email protected]
├── [email protected]
├── [email protected]
├── [email protected]
├── [email protected]
├── [email protected]
├── [email protected]
├── [email protected]
├── [email protected]
├── [email protected]
├── [email protected] ([email protected])
├── [email protected] ([email protected])
├── [email protected] ([email protected], [email protected])
├── [email protected] ([email protected], [email protected], [email protected], [email protected], http
[email protected])
├── [email protected] ([email protected], [email protected])
└── [email protected] ([email protected], [email protected])

[email protected] node_modules\body-parser
├── [email protected]
├── [email protected]
├── [email protected]
├── [email protected]
├── [email protected]
├── [email protected] ([email protected])
├── [email protected] ([email protected], [email protected])
├── [email protected] ([email protected], [email protected], [email protected])
└── [email protected] ([email protected], [email protected])

E:\test\mongo>
再來,搞定了^-^
E:\test\mongo>node app
app is listening at port 3000
資料庫連線成功


4.對資料庫進行操作

插入資料到資料庫:

增加下面程式碼
var insertDocument = function(db, callback) {
   //連線表
   var collection =db.collection('first'); 
   var user={
     name:'Dandy',
     age:18
   }
   //插入資料
   collection.insertOne( user, function(err, result) { 
     if(err){
       console.log(err)
     }
     console.log("插入成功"); 
     callback();
  });
};
修改資料庫連線程式碼
MongoClient.connect(url, function(err, db) {
  console.log("資料庫連線成功");
  insertDocument(db,function(){ 
    db.close();
  })
});
插入成功
E:\test\mongo>node app
app is listening at port 3000
資料庫連線成功
插入成功


查詢資料庫中資料:

增加如下程式碼
var findRestaurants = function(db, callback) {
   var cursor =db.collection('first').find( );
   cursor.each(function(err, result) { 
      if (result != null) {
         console.log(result);
      } else {
         callback();
      }
   });
};
修改資料庫連線程式碼
MongoClient.connect(url, function(err, db) {
  console.log("資料庫連線成功");
  findRestaurants(db, function() {
      db.close();
  });
});
查詢成功(ctrl+c可以關閉node服務)
E:\test\mongo>node app
app is listening at port 3000
資料庫連線成功
插入成功
^C
E:\test\mongo>node app
app is listening at port 3000
資料庫連線成功
{ _id: 56fc8e6d58257d7101dfafa0, name: 'tom', age: 13 }
{ _id: 56fc907858257d7101dfafa2, name: 'tom2', age: 2 }
{ _id: 56fc907858257d7101dfafa3, name: 'tom3', age: 3 }
{ _id: 56fc907858257d7101dfafa4, name: 'tom4', age: 4 }
{ _id: 56fc907858257d7101dfafa5, name: 'tom5', age: 5 }
{ _id: 56fc907858257d7101dfafa6, name: 'tom6', age: 6 }
{ _id: 56fc907858257d7101dfafa7, name: 'tom7', age: 7 }
{ _id: 56fc907858257d7101dfafa8, name: 'tom8', age: 8 }
{ _id: 56fc907858257d7101dfafa9, name: 'tom9', age: 9 }
{ _id: 56fccb1c8865f98415ed939f, name: 'Dandy', age: 18 }
條件查詢: 修改findRestaurants程式碼
var findRestaurants = function(db, callback) {
   var cursor =db.collection('first').find({name:'Dandy'} );
   cursor.each(function(err, result) { 
      if (result != null) {
         console.log(result);
      } else {
         callback();
      }
   });
};
查詢成功
E:\test\mongo>node app
app is listening at port 3000
資料庫連線成功
{ _id: 56fccb1c8865f98415ed939f, name: 'Dandy', age: 18 }

or查詢: 修改findRestaurants程式碼
var findRestaurants = function(db, callback) {
   var cursor =db.collection('first').find({$or :[{name:'Dandy'},{age:3}]});
   cursor.each(function(err, result) { 
      if (result != null) {
         console.log(result);
      } else {
         callback();
      }
   });
};
查詢成功
E:\test\mongo>node app
app is listening at port 3000
資料庫連線成功
{ _id: 56fc907858257d7101dfafa3, name: 'tom3', age: 3 }
{ _id: 56fccb1c8865f98415ed939f, name: 'Dandy', age: 18 }

修改資料庫中資料

增加如下程式碼
var updateRestaurants = function(db, callback) {
 var collection =db.collection('first'); 
 collection.updateOne({name:"Dandy"},{$set: {age:13}}, function(err, results) {
      console.log(results.result);
      callback();
 });
};
修改資料庫連線程式碼
MongoClient.connect(url, function(err, db) {
  console.log("資料庫連線成功");
  updateRestaurants(db, function() {
    findRestaurants(db,function(){
      db.close();
    })
  });
});
修改成功
E:\test\mongo>node app
app is listening at port 3000
資料庫連線成功
{ ok: 1, nModified: 0, n: 1 }
{ _id: 56fc907858257d7101dfafa3, name: 'tom3', age: 3 }
{ _id: 56fccb1c8865f98415ed939f, name: 'Dandy', age: 13 }

刪除資料庫中資料

增加如下程式碼
var removeRestaurants = function(db, callback) {
  var collection =db.collection('first'); 
  collection.deleteMany(
      { name: "tom2" },
      function(err, results) {
         console.log(results.result);
         callback();
      }
   );
};
修改findRestaurants程式碼(改為查詢所有)
var findRestaurants = function(db, callback) {
   var cursor =db.collection('first').find();
   cursor.each(function(err, result) { 
      if (result != null) {
         console.log(result);
      } else {
         callback();
      }
   });
};
修改資料庫連線程式碼
MongoClient.connect(url, function(err, db) {
  console.log("資料庫連線成功");
  removeRestaurants(db, function() {
    findRestaurants(db,function(){
      db.close();
    })
  });
});
刪除成功
E:\test\mongo>node app
app is listening at port 3000
資料庫連線成功
{ ok: 1, n: 0 }
{ _id: 56fc8e6d58257d7101dfafa0, name: 'tom', age: 13 }
{ _id: 56fc907858257d7101dfafa3, name: 'tom3', age: 3 }
{ _id: 56fc907858257d7101dfafa4, name: 'tom4', age: 4 }
{ _id: 56fc907858257d7101dfafa5, name: 'tom5', age: 5 }
{ _id: 56fc907858257d7101dfafa6, name: 'tom6', age: 6 }
{ _id: 56fc907858257d7101dfafa7, name: 'tom7', age: 7 }
{ _id: 56fc907858257d7101dfafa8, name: 'tom8', age: 8 }
{ _id: 56fc907858257d7101dfafa9, name: 'tom9', age: 9 }
{ _id: 56fccb1c8865f98415ed939f, name: 'Dandy', age: 13 }


5.其他

本文並沒有對程式碼進行分層結構化,但是建議最好還是分層。
學習了本節我們能夠簡單的對資料庫進行增刪改查。