MongoDB 数据库

安装

安装 homebrew
  • 安装时会报错
curl: (7) Failed to connect to raw.githubusercontent.com port 443: Connection refused

打开 https://www.ipaddress.com/ 输入访问不了的域名
查询到该网址 ip,然后在 hosts 文件中添加

185.199.108.133	raw.githubusercontent.com

之后又会报

curl: (35) LibreSSL SSL_connect: SSL_ERROR_SYSCALL in connection to raw.githubusercontent.com:443

最后使用国内源

/bin/zsh -c "$(curl -fsSL https://gitee.com/cunkai/HomebrewCN/raw/master/Homebrew.sh)"
  • 更新 brew 版本
brew update

安装 mongodb

进入 github mongodb/homebrew-brew
查找指令

  • 安装
brew services stop mongodb
brew uninstall mongodb
brew tap mongodb/brew
brew install mongodb-community
  • 启动
brew services start mongodb-community
  • 停止
brew services stop mongodb-community

安装 compass

进入 mongodb 官网
Software 菜单下 compass 点击进入下载

命令行

显示所有数据库

show dbs

进入某个数据库

use comments

显示数据库中的集合

show collections

插入数据

db.users.insert({ username: 'wangwu', password: 'abc' })

查询数据

db.users.find()
db.users.find({ city: 'shanghai' })
# 排序
db.users.find().sort({age: 1})

bson

  • JSON 是一种常用的数据格式
  • JSON 是字符串类型的
  • BSON = Binary JSON 即二进制类型的 JSON

NoSQL

mongodb 连接 nodejs

  • 安装 npm 包
npm i mongodb --save
const MongoClient = require('mongodb').MongoClient

const url = 'mongodb://localhost:27017'
const dbName = 'comment1'

MongoClient.connect(url, {
	useUnifiedTopology: true,
	useNewUrlParser: true
}, (err, client) => {
	if (err) {
		console.error('mongodb 连接失败', err)
		return
	}
	console.log('mongodb 连接成功')

	const db = client.db(dbName)	// 切换数据库
	const userCollection = db.collection('users')	// 切换集

	client.close()
})

查询数据

...
userCollection.find().toArray((err, result) => {
	if (err) {
		console.error('查询数据出错', err)
		return
	}
	console.log('查询结果', result)
})
...

插入数据

userCollection.insertOne({
	username: 'liuliu',
	password: 'abc',
	age: 36,
	city: 'shenzhen'
}, (err, result) => {
	if (err) {
		console.error('插入错误', err)
		return
	}
	console.log('插入成功', result.insertedCount, result.insertedId)
})

更新数据

userCollection.updateOne({ username: 'zhangsan' }, {
	$set: {
		city: 'nanjing',
		age: 23
	}
}, (err, result) => {
	if (err) {
		console.error('更新错误', err)
		return
	}
	console.log('更新成功', result.modifiedCount)
})

删除数据

userCollection.deleteOne({ username: 'wangwu' }, (err, result) => {
	if (err) {
		console.error('删除失败', err)
		return
	}
	console.log('删除成功')
}) 

mongoose

mongoose 可提供规范

  • Schema 定义数据格式的规范
  • 以 Model 规范 Collection
  • 规范数据操作的 API
// db.js
const mongoose = require('mongoose')
const url = 'mongodb://localhost:27017'
const dbName = 'comment2'

mongoose.set('useCreateIndex', true)
mongoose.set('useFindAndModify', false)

mongoose.connect(`${url}/${dbName}`, {
	useNewUrlParser: true,
	useUnifiedTopology: true
})

const conn = mongoose.connection

conn.on('error', err => {
	console.error('mongoose 连接出错', err)
})

module.exports = mongoose
// model.js
const mongoose = require('./db')

const UserSchema = mongoose.Schema({
	username: {
		type: String,
		required: true,
		unique: true
	},
	password: String,
	age: Number,
	city: String,
	gender: {
		type: Number,
		default: 0
	}
}, {
	timestamps: true
})
const User = mongoose.model('user', UserSchema)
module.exports = { 
	User
}
// test.js
const { User } = require('./model.js')

!(async function() {
	// 新增
	const zhangsan = User.create({
		username: 'zhangsan',
		password: 'abc',
		age: 22,
		city: 'beijing',
		gender: 1
	})
	console.log(zhangsan)
	
	// 查询
	const userList = User.find()
	console.log(userList)

	// 查询单条
	const user = User.findOne({ username: 'zhangsan' })
	console.log(user)
	
	// 根据 id 查询条数据
	const id= '60a5bda1af04c90489ec4e0c'
	const user = User.findById(id)
	console.log(user)

	// 更新数据
	const updateResult = await User.findOneAndUpdate(
		{ username: 'zhangsan' },
		{ age: 20 },
		{
			new: true
		}
	)
	console.log(updateResult)

	// 删除数据
	const removeResult = await User.remove({ username: 'zhangsan' })
	console.log(removeResult)
})()
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值