1.数据库字段的设计:
1.1.在数据库moon中新建表格“MakeUp”
1.2.具体的字段含义:
brand: "", //商品的类型
careType:" ", //护理类型 //可选值:facialCare:面部护理类型 ; perfumeCosmetics:香水彩妆类型 ;img:[ ],//商品图片
useType:" " , //用途类型,可选值:“口红” ;“化妆工具” ;“BB霜” ; “防晒霜” ;“洗面奶” ; “水” ; “乳”; ...........等
originPrice:number , //未打折价格
newPrice:number , //打折价格
goodsName:" " , //商品名称
goodsDescribe:" " ,//商品描述
goodsDetail:" " ,//商品详情,在商品详情中的商品详情描述图片,是一个字符串类型的图片地址
stock:number , //库存量
monthlySales:number , //月销售量
SalesCount:number, //总销售量
productionPlace:"" //产地
2.mongoose的使用:
2.1.基于对新知识的学习热情,虽然前面是有用到对mongodb的封装allhandlers.js,,基本可以达到我目前的功能,但是基于好奇现在开发的话用mongodb大多数可能都选择用mongoose来过度使用mongodb,so我也去研究了下,前面有博文写到基本的mongoose的使用,个人是感觉使用mongoose的话,会让mongo数据库在使用时更容易语义化,和操作,更稳定吧。
2.2.进入后台项目文件夹routes 新建文件夹Model,在里面新建文件AllHandler.js文件,对mongoose操作做一个基本的增删改查的封装,具体代码如下:
var assert = require(‘assert‘); //断言包 //这个页面来封装基本的增删改查的方法 //增 var add = function(Mod, selector, fn) { //参数1是实例化的Model,参数2是需要新增的内容 var model = new Mod(selector[0]); try { model.save(function(err, res) { assert.equal(err, null); fn(res) }) } catch (ex) { console.log("AllHandler报错:" + ex); fn([]); } } //查 //查所有根据条件 var find = function(Mod, selector, fn) { try { Mod.find(selector[0], selector[1] ? selector[1] : "", function(err, res) { assert.equal(err, null); fn(res) }) } catch (ex) { console.log("AllHandler报错:" + ex); fn([]); } } //通过ID更新某条数据 var updateById = function(Mod, selector, fn) { var id = selector[0].id; var updatestr = selector[1]; try { Mod.findByIdAndUpdate(id, updatestr, function(err, res) { if (err) { assert.equal(err, null); } else { fn(res); } }) } catch (ex) { console.log("AllHandler报错:" + ex); fn(null); } }; //通过ID来删除一条数据 var deleteById = function(Mod, selector, fn) { var id = selector[0].id; try { Mod.findByIdAndRemove(id, function(err, res) { if (err) { assert.equal(err, null); } else { fn(res); } }) } catch (ex) { console.log("AllHandler报错:" + ex); fn(null); } }; //通过条件来删除所有符合条件的 var deleteByStr = function(Mod, selector, fn) { var conditions = selector[0]; try { Mod.remove(conditions, function(err, res) { if (err) { assert.equal(err, null); } else { fn(res); } }) } catch (ex) { console.log("AllHandler报错:" + ex); fn(null); } } //分页 var page = function(Mod, selector, fn) { var pageSize = selector[1].pageSize || 5; //一页多少条 var currentPage = selector[1].currentPage || 1; //当前第几页 var skipnum = (currentPage - 1) * pageSize; //跳过数 try { var results; var count; Mod.count(selector[0], function(err, result2) { assert.equal(err, null); count = result2; }); /* Mod.find({}, function(err, res) { //在mongoose中第一个参数查询条件必须是一个json集合对象,如果是空写成{},而不能是“”; assert.equal(err, null); console.log(res) fn(res) })*/ Mod.find(selector[0]).skip(skipnum).limit(pageSize).exec(function(err, res) { //console.log("hahaha") assert.equal(err, null); if (res) { results = res; //console.log(count, results) fn(results, count); } }); } catch (ex) { console.log("AllHandler报错:" + ex); } } var OperateType = { add: add, find: find, findSome: find, page: page, deleteByStr: deleteByStr, deleteById: deleteById, updateById: updateById }; module.exports = function(Mod, i, selector, fn) { //model ; 参数 ; 回调函数 OperateType[i](Mod, selector, fn); }
2.3.然后还是继续在上面的Model文件夹中,新建一个基本连接的文件MyMongoose.js文件,进行连接数据库操作,具体代码如下:
var mongoose = require(‘mongoose‘); var Url = "mongodb://localhost:27017/moon"; //要用到的数据库moon; var db = mongoose.connect(Url); // 监听连接成功 mongoose.connection.on(‘connected‘, function() { console.log("成功连接到数据库:" + Url) }) //监听连接异常 mongoose.connection.on(‘error‘, function(err) { console.log("连接数据库出现异常:" + err) }) //监听连接断开 mongoose.connection.on(‘disconnected‘, function() { console.log(‘连接数据库现在已经断开‘) }) module.exports = { mongoose: mongoose, db: db };
2.4.然后还是在routes文件夹中新建文件ModelMakeUp.js,去定义化妆品表格的model的schema,以及增删改差的操作路由等,具体代码如下:
//MakeUp表的数据库操作 var express = require(‘express‘); var router = express.Router(); var crypto = require(‘crypto‘); var ObjectId = require(‘mongodb‘).ObjectId; var mongoose = require(‘./Model/MyMongoose‘).mongoose; var handle = require(‘./Model/AllHandler‘); var formidable = require(‘formidable‘); var fs = require(‘fs‘); /* brand: "", //商品的类型 careType:" ", //护理类型 //可选值:facialCare:面部护理类型 ; perfumeCosmetics:香水彩妆类型 ;img:[ ],//商品图片 useType:" " , //用途类型,可选值:“口红” ;“化妆工具” ;“BB霜” ; “防晒霜” ;“洗面奶” ; “水” ; “乳”; ...........等 originPrice:number , //未打折价格 newPrice:number , //打折价格 goodsName:" " , //商品名称 goodsDescribe:" " ,//商品描述 goodsDetail:" " ,//商品详情,在商品详情中的商品详情描述图片,是一个字符串类型的图片地址 stock:number , //库存量 monthlySales:number , //月销售量 SalesCount:number, //总销售量 productionPlace:"" //产地 */ var schema = mongoose.Schema; var MakeUpSch = new schema({ //这个表的字段 goodsName: String, goodsDescribe: String, goodsDetail: String, brand: String, careType: String, useType: String, originPrice: Number, newPrice: Number, productionPlace: String, img: { type: String, default: "http://localhost:3000/images/makeUp/啦.jpg" }, stock: Number, SalesCount: Number, monthlySales: Number }); var MolMakeUp = mongoose.model(‘MakeUp‘, MakeUpSch, ‘MakeUp‘); //往表格里面插数据 router.post(‘/add‘, function(req, res) { var collection = []; if (req.body.collection.img == "") { req.body.collection.img = "http://localhost:3000/images/makeUp/啦.jpg" } collection[0] = req.body.collection; handle(MolMakeUp, ‘add‘, collection, function(result) { res.send(result) }) }) //查询表里所有数据 router.post("/find", function(req, res) { var collection = [{}]; handle(MolMakeUp, ‘find‘, collection, function(result) { res.send(result) }) }) //查询表里符合条件的数据,并且筛选只要部分字段 router.post("/findSome", function(req, res) { var collection = [{}, {}]; collection[1] = req.body.show; handle(MolMakeUp, ‘find‘, collection, function(result) { res.send(result) }) }) //根据ID删除表格的数据 router.post("/deleteById", function(req, res) { var id = req.body.id; var collection = []; collection[0] = { id: ObjectId(id) }; handle(MolMakeUp, "deleteById", collection, function(result) { res.send(result) }) }) //根据ID来update更新数据 router.post("/updateById", function(req, res) { var id = req.body.selector._id; var collection = []; collection[0] = { id: ObjectId(id) }; if (req.session.makeUp_imgPath != "" && req.session.makeUp_imgPath != null) { req.body.selector.img = req.session.makeUp_imgPath; console.log(req.body.selector.img[0]); console.log(req.session.makeUp_imgPath); } collection[1] = req.body.selector; handle(MolMakeUp, "updateById", collection, function(result) { res.send(result) }) }) //分页查询 router.post(‘/page‘, function(req, res) { var selector = []; selector[0] = {}; selector[1] = { pageSize: req.body.rows, //每页展示几条数据 currentPage: req.body.page //当前在第几页 }; //res.send("111") handle(MolMakeUp, ‘page‘, selector, function(result, count) { var result = { result: result, count: count } res.send(result); }) }) //wangEditor编辑器接口 //wangeditor上传图片的地址 router.post("/wangeditor/upload", function(req, res, next) { var form = new formidable.IncomingForm(); //设置文件上传存放地址 form.uploadDir = "./public/images/makeUp"; //执行里面的回调函数的时候,表单已经全部接收完毕了。 form.parse(req, function(err, fields, files) { //if(files.File){ var oldpath = files.myFileName.path; var extname = files.myFileName.name; //新的路径由三个部分组成:时间戳、随机数、拓展名 var newpath = "./public/images/makeUp/" + extname; //改名 try { fs.rename(oldpath, newpath, function(err) { if (err) { res.json({ errno: 1, data: [] }); }; var mypath = newpath.replace("./public", "http://localhost:3000"); req.session.makeUp_imgPath = mypath; res.json({ errno: 0, data: [mypath] }) }); } catch (ex) { res.json({ errno: 1, data: null }) } }); }) module.exports = router;
3.修改路由,让能访问到上面的路径,进入routes里面的routes.js修改成下面的代码:
// 主要的路由文件 module.exports = function(app) { app.use(‘/‘, require(‘./index‘)) app.use(‘/users‘, require(‘./users‘)) app.use(‘/ModelMakeUp‘, require(‘./ModelMakeUp‘)) //加这个 }
原文地址:https://www.cnblogs.com/chun321/p/9203267.html