前端那些事之mongodb

2019独角兽企业重金招聘Python工程师标准>>> hot3.png

mongodb的安装及配置

  • 下载地址mongodb下载地址 前端那些事之mongodb_第1张图片

配置地址:

  • 安装好设置数据库地址: 例如:在e盘目录新建文件夹MongoDB,在MongoDB文件夹中新建三个文件夹 分别是:data(存放数据的路径),ect(配置数据库文件),logs(数据库日志)

前端那些事之mongodb_第2张图片

  • 在etc文件夹中设置配置文件,新建mongo.conf配置文件
dbpath=E:\MongoDB\data\ #数据库路径  
logpath=E:\MongoDB\logs\mongo.log #日志输出配置
journal=true #启用日志文件,默认启用  
quiet=true #这个选项可以过滤掉一些无用的日志信息,若需要调试使用请设置为false  
port=27017 #端口号 默认为27017
httpinterface=true #http配置  启动28017端口查看网页信息
  • 在logs文件夹中新建mongo.log文件
  • 启动
  • 1打开cmd,以管理员方式进入

前端那些事之mongodb_第3张图片

  • 2 找到c盘mongodb的路径

前端那些事之mongodb_第4张图片

  • 3:(mongodb3.4,使用mongovue能创建collection)通过mongod --storageEngine mmapv1 --dbpath +路径设置数据的路径

前端那些事之mongodb_第5张图片

  • 4:指定配置文件路径

前端那些事之mongodb_第6张图片

  • 5:添加本地service

  • 前端那些事之mongodb_第7张图片

  • 然后在打开本地服务

前端那些事之mongodb_第8张图片

  • 点击允许开启服务

前端那些事之mongodb_第9张图片

  • 4:配置环境变量

前端那些事之mongodb_第10张图片

  • 5 启动mogodb

前端那些事之mongodb_第11张图片

  • 6 mongodb的插件数据
  • 新建一个dumall-goods文本,不要后缀名
{"_id":{"$oid":"58c284b13a1bb9aa7033801b"},"productId":"201710003","productName":"平衡车","salePrice":1999,"productImage":"pingheng.jpg","productUrl":""}
{"_id":{"$oid":"58c284d7117a2e6599abef5e"},"productId":"201710004","productName":"头戴式耳机-3","salePrice":80,"productImage":"2.jpg","productUrl":""}
{"_id":{"$oid":"58c284e6117a2e6599abef5f"},"productId":"201710005","productName":"小米笔记本","salePrice":3549,"productImage":"note.jpg","productUrl":""}
{"_id":{"$oid":"58c284f4117a2e6599abef60"},"productId":"201710006","productName":"小米6","salePrice":2499,"productImage":"mi6.jpg","productUrl":""}
{"_id":{"$oid":"58e704ef98dab115d336b3f1"},"productId":"201710002","productName":"智能插线板","salePrice":59,"productImage":"6.jpg","productUrl":""}
{"_id":{"$oid":"58e7050398dab115d336b3f2"},"productId":"201710007","productName":"自拍杆","salePrice":39,"productImage":"zipai.jpg","productUrl":""}
{"_id":{"$oid":"58e7050c98dab115d336b3f3"},"productId":"201710008","productName":"小米净水器","salePrice":1999,"productImage":"8.jpg","productUrl":""}
{"_id":{"$oid":"58e7051698dab115d336b3f4"},"productId":"201710009","productName":"IH 电饭煲","salePrice":999,"productImage":"9.jpg","productUrl":""}
{"_id":{"$oid":"58e7052198dab115d336b3f5"},"productId":"201710010","productName":"小米电视4A","salePrice":2099,"productImage":"10.jpg","productUrl":""}

在终端输入 
mongoimport导入,-d:数据库名称,-c:collection名称, --file:是导入的路径
mongoimport -d demo -c dbdemo --file C:\Users\Administrator\Desktop\dumall-goods

mongoose 的应用

  • 创建mongo数据库
  • 在cmd里执行mongo

前端那些事之mongodb_第12张图片

  • show dbs (查看所有的数据库)

前端那些事之mongodb_第13张图片

  • use db_demo(数据库名称 ) 前端那些事之mongodb_第14张图片
  • db.createCollection("goods") ** 注意:创建collection的时候一定要加s ,否则mongoose连接mongo连接不上**
  • show collections(查看所有的colletion(集合))

前端那些事之mongodb_第15张图片

  • 插入数据(重新打开一个cmd) mongoimport -d dbdemo -c tests --file C:\Users\Administrator\Desktop\dumall-goods

前端那些事之mongodb_第16张图片

前端那些事之mongodb_第17张图片

mongoose 安装

cnpm install mongoose --save

  • modles文件里新goods.js 前端那些事之mongodb_第18张图片
const mongoose = require('mongoose')
const Schema = mongoose.Schema

let productSchema = new Schema({
  'productId':{type:String},
  'productName':String,
  'salePrice':Number,
  'checked':String,
  'productNum':Number,
  'productImage':String
})

module.exports = mongoose.model('Good', productSchema)

  • 在router 文件夹下创建goods.js

前端那些事之mongodb_第19张图片

const express = require('express')
const router = express.Router()
const mongoose = require('mongoose')
const Goods = require('../models/goods')

//去除连接mongobd警告信息
var options = {
  useMongoClient: true,
  autoIndex: false, // Don't build indexes
  reconnectTries: Number.MAX_VALUE, // Never stop trying to reconnect
  reconnectInterval: 500, // Reconnect every 500ms
  poolSize: 10, // Maintain up to 10 socket connections
  // If not connected, return errors immediately rather than waiting for reconnect
  bufferMaxEntries: 0
};
//连接数据库
let data = mongoose.connect('mongodb://127.0.0.1:27017/mock',options)

mongoose.connection.on("connected", () => {
  console.log('MongoDB connected suceess');
})

mongoose.connection.on("error", () => {
  console.log('MongoDB connected fail.');
})

mongoose.connection.on("disconnected", () => {
  console.log('MongoDB connected disconnected');
})

// console.log(data);
console.log(data.collections.goods.findOne({productId : 201710003 }));

//查询商品列表
router.get("/list",(req, res, next) => {

  Goods.find({},(err, doc) => {
    if(err){
      res.json({
        status:'1',
        message:err.message
      })
    }else{
      res.json({
        status:'0',
        message:'成功',
        result:{
          count:doc.length,
          list:doc
        }
      })
    }

  })
})
module.exports = router

  • 在app.js里面添加 goods路由
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');

var index = require('./routes/index');
var users = require('./routes/users');
//添加 goods 路由
var goods = require('./routes/goods')

var app = express();

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');

// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

app.use('/', index);
app.use('/users', users);
//使用goods路由
app.use('/goods', goods)

// catch 404 and forward to error handler
app.use(function(req, res, next) {
  var err = new Error('Not Found');
  err.status = 404;
  next(err);
});
  • 启动:cd server , node bin\www

前端那些事之mongodb_第20张图片

  • 访问

前端那些事之mongodb_第21张图片

  • config文件夹中index.js更改访问

前端那些事之mongodb_第22张图片

  • index.js

'use strict'
// Template version: 1.1.3
// see http://vuejs-templates.github.io/webpack for documentation.

const path = require('path')

module.exports = {
  build: {
    env: require('./prod.env'),
    index: path.resolve(__dirname, '../dist/index.html'),
    assetsRoot: path.resolve(__dirname, '../dist'),
    assetsSubDirectory: 'static',
    assetsPublicPath: '/',
    productionSourceMap: true,
    // Gzip off by default as many popular static hosts such as
    // Surge or Netlify already gzip all static assets for you.
    // Before setting to `true`, make sure to:
    // npm install --save-dev compression-webpack-plugin
    productionGzip: false,
    productionGzipExtensions: ['js', 'css'],
    // Run the build command with an extra argument to
    // View the bundle analyzer report after build finishes:
    // `npm run build --report`
    // Set to `true` or `false` to always turn it on or off
    bundleAnalyzerReport: process.env.npm_config_report
  },
  dev: {
    env: require('./dev.env'),
    port: process.env.PORT || 8099,
    autoOpenBrowser: true,
    assetsSubDirectory: 'static',
    assetsPublicPath: '/',
    proxyTable: {
      '/goods':{
        target:'http://localhost:3001'
      },
      '/goods/*':{
        target:'http://localhost:3001'
      },
    },
    // CSS Sourcemaps off by default because relative paths are "buggy"
    // with this option, according to the CSS-Loader README
    // (https://github.com/webpack/css-loader#sourcemaps)
    // In our experience, they generally work as expected,
    // just be aware of this issue when enabling this option.
    cssSourceMap: false
  }
}

分页逻辑

router.get("/list",(req, res, next) => {
  
  let page = parseInt(req.param("page"))
  let pagSize = parseInt(req.param("pageSize"))
  let sort = req.param("sort")
  let skip = (page-1)*pagSize
  let params = {}
  let goodsModel = Goods.find(params)
    .skip(skip)
    .limit(pagSize)
    .sort({'salePrice':sort})
    .exec((err, doc) => {
      if(err){
        res.json({
          status:'1',
          message:err.message
        })
      }else{
        res.json({
          status:'0',
          message:'成功',
          result: {
            count:doc.length,
            list:doc
          }
        })
      }

    })

})

转载于:https://my.oschina.net/yongxinke/blog/1572297

你可能感兴趣的:(前端那些事之mongodb)