基于NodeJS+MongoDB+AngularJS+Bootstrap开发书店案例分析(2)

/** * Module dependencies. */ var express = require('express') , routes = require('./routes') , books = require('./routes/books') , http = require('http') , path = require('path'); var app = express(); // all environments app.set('port', process.env.PORT || 3000); app.set('views', __dirname + '/views'); app.set('view engine', 'ejs'); app.use(express.favicon()); app.use(express.logger('dev')); app.use(express.bodyParser()); app.use(express.methodOverride()); app.use(app.router); app.use(express.static(path.join(__dirname, 'public'))); // development only if ('development' == app.get('env')) { app.use(express.errorHandler()); } app.get('https://www.jb51.net/', books.list); app.get('/books', books.list); http.createServer(app).listen(app.get('port'), function(){ console.log('Express server listening on port ' + app.get('port')); });

四、Monk访问MongoDB数据库

monk是NodeJS平台下访问MongoDB数据库的一个模块。monk访问MongoDB更加方便比NodeJS直接访问。

git仓库地址:https://github.com/Automattic/monk

文档:https://automattic.github.io/monk/

安装:npm install --save monk

基于NodeJS+MongoDB+AngularJS+Bootstrap开发书店案例分析

4.1、创建连接

const monk = require('monk') // Connection URL const url = 'localhost:27017/myproject'; const db = monk(url); db.then(() => { console.log('Connected correctly to server') })

4.2、插入数据

const url = 'localhost:27017/myproject'; // Connection URL const db = require('monk')(url); const collection = db.get('document') collection.insert([{a: 1}, {a: 2}, {a: 3}]) .then((docs) => { // docs contains the documents inserted with added **_id** fields // Inserted 3 documents into the document collection }).catch((err) => { // An error happened while inserting }).then(() => db.close()) users.insert({ woot: 'foo' }) users.insert([{ woot: 'bar' }, { woot: 'baz' }])

4.3、更新数据

const url = 'localhost:27017/myproject'; // Connection URL const db = require('monk')(url); const collection = db.get('document') collection.insert([{a: 1}, {a: 2}, {a: 3}]) .then((docs) => { // Inserted 3 documents into the document collection }) .then(() => { return collection.update({ a: 2 }, { $set: { b: 1 } }) }) .then((result) => { // Updated the document with the field a equal to 2 }) .then(() => db.close()) users.update({name: 'foo'}, {name: 'bar'})

4.4、删除数据

const url = 'localhost:27017/myproject'; // Connection URL const db = require('monk')(url); const collection = db.get('document') collection.insert([{a: 1}, {a: 2}, {a: 3}]) .then((docs) => { // Inserted 3 documents into the document collection }) .then(() => collection.update({ a: 2 }, { $set: { b: 1 } })) .then((result) => { // Updated the document with the field a equal to 2 }) .then(() => { return collection.remove({ a: 3}) }).then((result) => { // Deleted the document with the field a equal to 3 }) .then(() => db.close()) users.remove({ woot: 'foo' })

4.5、查找数据

const url = 'localhost:27017/myproject'; // Connection URL const db = require('monk')(url); const collection = db.get('document') collection.insert([{a: 1}, {a: 2}, {a: 3}]) .then((docs) => { // Inserted 3 documents into the document collection }) .then(() => collection.update({ a: 2 }, { $set: { b: 1 } })) .then((result) => { // Updated the document with the field a equal to 2 }) .then(() => collection.remove({ a: 3})) .then((result) => { // Deleted the document with the field a equal to 3 }) .then(() => { return collection.find() }) .then((docs) => { // docs === [{ a: 1 }, { a: 2, b: 1 }] }) .then(() => db.close())

users.find({}).then((docs) => {}) users.find({}, 'name').then((docs) => { // only the name field will be selected }) users.find({}, { fields: { name: 1 } }) // equivalent users.find({}, '-name').then((docs) => { // all the fields except the name field will be selected }) users.find({}, { fields: { name: 0 } }) // equivalent users.find({}, { rawCursor: true }).then((cursor) => { // raw mongo cursor }) users.find({}).each((user, {close, pause, resume}) => { // the users are streaming here // call `close()` to stop the stream }).then(() => { // stream is over }) //创建的数据库 var monk = require('monk') var db = monk('localhost:27017/bookstore') //读取数据: var monk = require('monk') var db = monk('localhost:27017/monk-demo') var books = db.get('books') books.find({}, function(err, docs) { console.log(docs) }) //插入数据: books.insert({"name":"orange book","description":"just so so"}) //查找数据: books.find({"name":"apple book"}, function(err, docs) { console.log(docs) }) 复制代码 五、创建Rest后台服务 在routes目录下增加的books.js文件内容如下: 复制代码 /* * 使用monk访问mongodb * 以rest的方式向前台提供服务 */ //依赖monk模块 var monk = require('monk'); //连接并打开数据库 var db = monk('localhost:27017/BookStore'); //从数据库中获得books集合,类似表,并非所有数据, key var books = db.get('books'); //列出所有的图书json exports.list = function(req, res) { //无条件查找所有的图书,then是当查找完成时回调的异步方法 books.find({}).then((docs) => { //返回json给客户端 res.json(docs); }).then(() => db.close()); //关闭数据库 }; //获得最大id exports.getMax=function(req,res){ //找一个,根据id降序排序, books.findOne({}, {sort: {id: -1}}).then((bookObj)=>{ res.json(bookObj); }).then(() => db.close());; } //添加图书 exports.add = function(req, res) { //先找到最大的图书编号 books.findOne({}, {sort: {id: -1}}).then((obj)=>{ //从客户端发送到服务器的图书对象 var book=req.body; //设置图书编号为最大的图书编号+1 book.id=(parseInt(obj.id)+1)+""; //执行添加 books.insert(book).then((docs) => { //返回添加成功的对象 res.json(docs); }).then(() => db.close()); }); }; //删除图书 exports.del = function(req, res) { //从路径中取参数id,/:id var id=req.params.id; //移除编号为id的图书 books.remove({"id":id}).then((obj)=>{ //返回移除结果 res.json(obj); }).then(() => db.close()); }; //更新 exports.update = function(req, res) { //获得提交给服务器的json对象 var book=req.body; //执行更新,第1个参数是要更新的图书查找条件,第2个参数是要更新的对象 books.update({"id":book.id}, book).then((obj)=>{ //返回更新完成后的对象 res.json(obj); }).then(() => db.close()); };

为了完成跨域请求,修改http头部信息及路径映射,app.js文件如下:

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/wwdfpf.html