mongodb
mongodb
安装
- homebrew安装
brew update // 更新brew
brew install mongodb // 安装mongodb
- 设置数据路径
mongodb默认在/data/db这个路径进行读写操作,所以只要简单进行创建这个路径
mkdir -p /data/db
启动
- 启动服务
mongod
- 启动客户端,另开一个终端:
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')
})
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· DeepSeek 开源周回顾「GitHub 热点速览」
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了