项目作者: hzzly

项目描述 :
Express与MongoDB的水深火热
高级语言: JavaScript
项目地址: git://github.com/hzzly/express-mongodb.git
创建时间: 2017-03-25T10:45:59Z
项目社区:https://github.com/hzzly/express-mongodb

开源协议:MIT License

关键词:
express mongodb nodejs

下载


Express+MongoDB步步为’赢’

前奏

Express 是什么?

Express 是一个基于 Node.js 平台的极简、灵活的 web 应用开发框架,它提供一系列强大的特性,帮助你创建各种 Web 和移动设备应用。

全局安装express脚手架

  1. $ npm install express-generator -g

创建express项目

  1. $ express myapp
  2. $ cd myapp
  3. $ npm install
  4. $ DEBUG=myapp npm start

MongoDB与Mongoose?

  • MongoDB是一个对象数据库,是用来存储数据的;存储的数据格式为JSON。
  • Mongoose是封装了MongoDB操作(增删改查等)的一个对象模型库,是用来操作这些数据的。

安装MongoDB:
https://www.mongodb.com/download-center?jmp=nav

安装Mongoose:

  1. $ npm install mongoose --save

一、连接MongoDB

在项目根目录下新建/lib/mongo.js

  1. var mongoose = require("mongoose");
  2. var db = mongoose.connect('mongodb://localhost:27017/myblog');
  3. module.exports = db

要连接的数据库为myblog

二、Schema

一种以文件形式存储的数据库模型骨架,无法直接通往数据库端,不具备对数据库的操作能力,仅仅只是数据库模型在程序片段中的一种表现,可以说是数据属性模型(传统意义的表结构),又或着是“集合”的模型骨架

新建一个用户Schema

在项目根目录下新建/models/users.js

  1. var mongoose = require("mongoose");
  2. var db = require('../lib/mongo');
  3. //一个用户模型
  4. var UserSchema = new mongoose.Schema({
  5. username : { type:String },
  6. password : {type: String},
  7. avatar : {type: String},
  8. age : { type:Number, default:0 },
  9. description : { type: String},
  10. email : { type: String },
  11. github : { type: String },
  12. time : { type:Date, default:Date.now }
  13. });
  14. //创建Model
  15. var UserModel = db.model("user", UserSchema );
  16. module.exports = UserModel
  • user:数据库中的集合名称,当我们对其添加数据时如果user已经存在,则会保存到其目录下,如果不存在,则会创建user集合,然后在保存数据。
  • 拥有了Model,我们也就拥有了操作数据库的金钥匙,就可以使用Model来进行增删改查的具体操作。

Entity

由Model创建的实体,使用save方法保存数据,Model和Entity都有能影响数据库的操作,但Model比Entity更具操作性。

  1. var UserEntity = new UserModel({
  2. name : "hzzly",
  3. age : 21,
  4. email: "hjingren@aliyun.com",
  5. github: 'https://github.com/hzzly'
  6. });
  7. UserEntity.save(function(error,doc){
  8. if(error){
  9. console.log("error :" + error);
  10. }else{
  11. console.log(doc);
  12. }
  13. });

三、封装数据库的CURD

  • 在lib文件下新建api.js
  • 采用Promise封装对数据库的操作,避免回调地狱,使得代码能够更好的被读懂和维护。
  1. var UserModel = require('../models/users');
  2. module.exports = {
  3. /**
  4. * 添加数据
  5. * @param {[type]} data 需要保存的数据对象
  6. */
  7. save(data) {
  8. return new Promise((resolve, reject) => {
  9. //model.create(保存的对象,callback)
  10. UserModel.create(data, (error, doc) => {
  11. if(error){
  12. reject(error)
  13. }else{
  14. resolve(doc)
  15. }
  16. })
  17. })
  18. },
  19. find(data={}, fields=null, options={}) {
  20. return new Promise((resolve, reject) => {
  21. //model.find(需要查找的对象(如果为空,则查找到所有数据), 属性过滤对象[可选参数], options[可选参数], callback)
  22. UserModel.find(data, fields, options, (error, doc) => {
  23. if(error){
  24. reject(error)
  25. }else{
  26. resolve(doc)
  27. }
  28. })
  29. })
  30. },
  31. findOne(data) {
  32. return new Promise((resolve, reject) => {
  33. //model.findOne(需要查找的对象,callback)
  34. UserModel.findOne(data, (error, doc) => {
  35. if(error){
  36. reject(error)
  37. }else{
  38. resolve(doc)
  39. }
  40. })
  41. })
  42. },
  43. findById(data) {
  44. return new Promise((resolve, reject) => {
  45. //model.findById(需要查找的id对象 ,callback)
  46. UserModel.findById(data, (error, doc) => {
  47. if(error){
  48. reject(error)
  49. }else{
  50. resolve(doc)
  51. }
  52. })
  53. })
  54. },
  55. update(conditions, update) {
  56. return new Promise((resolve, reject) => {
  57. //model.update(查询条件,更新对象,callback)
  58. UserModel.update(conditions, update, (error, doc) => {
  59. if(error){
  60. reject(error)
  61. }else{
  62. resolve(doc)
  63. }
  64. })
  65. })
  66. },
  67. remove(conditions) {
  68. return new Promise((resolve, reject) => {
  69. //model.update(查询条件,callback)
  70. UserModel.remove(conditions, (error, doc) => {
  71. if(error){
  72. reject(error)
  73. }else{
  74. resolve(doc)
  75. }
  76. })
  77. })
  78. }
  79. }

使用

在/routers/index.js中使用

  1. var api = require('../lib/api');
  2. router.post('/login', function(req, res, next) {
  3. var user = {
  4. username : req.body.username,
  5. password: req.body.password
  6. };
  7. api.findOne(user)
  8. .then(result => {
  9. console.log(result)
  10. })
  11. })
  12. router.post('/sign_up', function(req, res, next) {
  13. var user = {
  14. username : req.body.username,
  15. password: req.body.password,
  16. email: req.body.email
  17. };
  18. api.save(user)
  19. .then(result => {
  20. console.log(result)
  21. })
  22. })
  23. router.get('/user_list', function(req, res, next) {
  24. //返回所有用户
  25. api.find({})
  26. .then(result => {
  27. console.log(result)
  28. })
  29. //返回只包含一个键值name、age的所有记录
  30. api.find({},{name:1, age:1, _id:0})
  31. .then(result => {
  32. console.log(result)
  33. })
  34. //返回所有age大于18的数据
  35. api.find({"age":{"$gt":18}})
  36. .then(result => {
  37. console.log(result)
  38. })
  39. //返回20条数据
  40. api.find({},null,{limit:20})
  41. .then(result => {
  42. console.log(result)
  43. })
  44. //查询所有数据,并按照age降序顺序返回数据
  45. api.find({},null,{sort:{age:-1}}) //1是升序,-1是降序
  46. .then(result => {
  47. console.log(result)
  48. })
  49. })

文章来源hzzly博客技术分享