mongodb

mongodb

安装

  1. homebrew安装
brew update  // 更新brew
brew install mongodb // 安装mongodb
  1. 设置数据路径

mongodb默认在/data/db这个路径进行读写操作,所以只要简单进行创建这个路径

mkdir -p /data/db

启动

  1. 启动服务
mongod
  1. 启动客户端,另开一个终端:
mongo

操作

在客户端的终端中:

show dbs
use foo
show collections
db.fruits.find()

使用

在nodejs中使用

const { MongoClient } = require('mongodb')
const client = new MongoClient('mongodb://localhost:27017',{useNewUrlParse:true})
client.connect(err=>{
  if(err) throw err
  // todo
})
const col = client.collection('fruits')
// 查找
col.find().skip((page - 1) * 5).limit(5).toArray()

db封装 > db.js :用事件派发订阅模式来解决异步回调

// 用事件派发订阅模式来解决异步回调
const config = require('../conf')
const { MongoClient } = require('mongodb')
const { EventEmitter } = require('events')
class MongodbClient {
  constructor(config) {
    this.config = config
    this.emitter = new EventEmitter()
    this.mongoClient = new MongoClient(config.url, {
      useNewUrlParser: true,
    }) // useNewUrlParse:true,解决:“不建议使用当前URL字符串解析器”警告

    this.mongoClient.connect((err) => {
      if (err) throw err
      console.log('连接成功')
      this.emitter.emit('connect')
    })
  }
  once(eventName, cb) {
    this.emitter.once(eventName, cb)
  }
  collection(colName, dbName = this.config.dbName) {
    return this.mongoClient.db(dbName).collection(colName)
  }
}

module.exports = new MongodbClient(config)

nodejs中简单server使用

const path = require('path')
const app = require('express')()
const mongoClient = require('./models/db')

app.get('/', (req, res) => {
  res.sendFile(path.resolve(__dirname, './index.html'))
})

app.get('/api/list', async (req, res) => {
  const { page, keyword, category } = req.query
  const conditions = {}
  keyword ? (conditions.name = { $regex: new RegExp(keyword) }) : ''
  category ? (conditions.category = category) : ''
  const col = mongoClient.collection('fruits')
  const total = await col.countDocuments()
  const data = await col
    .find(conditions)
    .skip((page - 1) * 5)
    .limit(5)
    .toArray()
  res.json({ ok: 200, data: { fruits: data, pagination: { total, page } } })
})

app.get('/api/category', async (req, res) => {
  const col = mongoClient.collection('fruits')
  const data = await col.distinct('category')
  console.log(data)
  res.json({ ok: 1, data })
})

app.listen(3003, () => {
  console.log('server is running at: http:localhost:3003')
})

原文地址:https://www.cnblogs.com/shine-lovely/p/15044138.html