前端知识学习

 

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
mongodb@2.1.14 node_modules\mongodb
├── es6-promise@3.0.2
├── readable-stream@1.0.31 (isarray@0.0.1, string_decoder@0.10.31, inherits@2
.0.1, core-util-is@1.0.2)
└── mongodb-core@1.3.13 (bson@0.4.22, require_optional@1.0.0)

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
ejs@2.3.4 node_modules\ejs

debug@2.2.0 node_modules\debug
└── ms@0.7.1

serve-favicon@2.3.0 node_modules\serve-favicon
├── etag@1.7.0
├── fresh@0.3.0
├── ms@0.7.1
└── parseurl@1.3.1

cookie-parser@1.3.5 node_modules\cookie-parser
├── cookie-signature@1.0.6
└── cookie@0.1.3

morgan@1.6.1 node_modules\morgan
├── on-headers@1.0.1
├── basic-auth@1.0.3
├── depd@1.0.1
└── on-finished@2.3.0 (ee-first@1.1.1)

express@4.13.4 node_modules\express
├── escape-html@1.0.3
├── array-flatten@1.1.1
├── content-type@1.0.1
├── serve-static@1.10.2
├── etag@1.7.0
├── range-parser@1.0.3
├── parseurl@1.3.1
├── vary@1.0.1
├── utils-merge@1.0.0
├── content-disposition@0.5.1
├── merge-descriptors@1.0.1
├── path-to-regexp@0.1.7
├── methods@1.1.2
├── cookie-signature@1.0.6
├── fresh@0.3.0
├── cookie@0.1.5
├── depd@1.1.0
├── qs@4.0.0
├── finalhandler@0.4.1 (unpipe@1.0.0)
├── on-finished@2.3.0 (ee-first@1.1.1)
├── proxy-addr@1.0.10 (forwarded@0.1.0, ipaddr.js@1.0.5)
├── send@0.13.1 (destroy@1.0.4, statuses@1.2.1, ms@0.7.1, mime@1.3.4, http
rors@1.3.1)
├── accepts@1.2.13 (negotiator@0.5.3, mime-types@2.1.10)
└── type-is@1.6.12 (media-typer@0.3.0, mime-types@2.1.10)

body-parser@1.13.3 node_modules\body-parser
├── bytes@2.1.0
├── content-type@1.0.1
├── depd@1.0.1
├── qs@4.0.0
├── iconv-lite@0.4.11
├── on-finished@2.3.0 (ee-first@1.1.1)
├── http-errors@1.3.1 (statuses@1.2.1, inherits@2.0.1)
├── raw-body@2.1.6 (unpipe@1.0.0, bytes@2.3.0, iconv-lite@0.4.13)
└── type-is@1.6.12 (media-typer@0.3.0, mime-types@2.1.10)

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.其他

本文并没有对代码进行分层结构化,但是建议最好还是分层。
学习了本节我们能够简单的对数据库进行增删改查。