安装mongodb
https://www.mongodb.com/try/download/community
运行 C:\Program Files\MongoDB\Server\3.4\bin 下mongod.exe
添加PATH环境变量C:\Program Files\MongoDB\Server\3.4\bin
控制台查看mongodb版本
mongod --version
mongodb启动
// mongodb 默认使用执行 mongod 命令所处盘符根目录下的
// /data/db 作为数据存储目录
// 第一次执行命令手动新建 /data/db文件夹
mongod // 启动本机mongodb服务
// 修改默认存储路径
mongod --dbpath=数据存储目录路径
关闭服务
// 开启服务的控制台 ctrl + c
// or 直接关闭启动服务的控制台
连接/退出数据库
// 默认连接本机的mongodb服务
mongo
// 退出
exit
基本命令
// 查看显示所有数据库
show dbs
// 查看当前操作的数据库
db
// 切换到指定数据库 没有则会新建
use 数据库名称
// 插入数据
db.students.insertOne({"name":"zs"})
// 显示集合
show collections
// 查找
db.students.find()
mongodb基本
// 数据库 --animals
// 集合 --cats
// 文档 --{}
animals:{
cats:[
{
name:'xiaohua',
color:'red'
},
{}
...
],
dogs:[]
...
}
安装mongoose
cnpm install mongoose --save
启动数据库
var mongoose = require('mongoose')
// 连接数据库
// 指定连接的数据库不需要存在 当插入第一条数据之后就会自动被创建出来
mongoose.connect('mongodb://localhost/itcast')
// 设计文档结构(表结构)
// 字段名称就是表结构中的属性名称
// 约束的目的是为了保证数据的完整性 不要有脏数据
var studentSchema = new mongoose.Schema({
name: {
type: String,
required: true
},
age: {
type: Number
}
})
// 将文档结构发布为模型
// mongoose.model 用来将一个架构发布为model
// mongoose.model('Student', studentSchema)
// 传入一个大写名词单数字符串用来表示你的数据库名称
// mongoose自动将大写名词的字符串生成 小写复数的集合名称
// studentSchema 架构Schema
// 返回值 模型构造函数
module.exports = mongoose.model('Student', studentSchema)
增删改查
// 新增
var zs = new Student({
name: 'zs',
age: 20
})
zs.save(function (err, ret) {
if (err) {
...
} else {
...
}
})
// 查找
Model.find({
id: xxx
}, function (err, ret) {
if (err) {
...
} else {
...
}
})
Model.findOne({
name: 'zs'
}, function (err, ret) {
if (err) {
...
} else {
...
}
})
// 删除
User.remove({
id: xxx
}, function (err, ret) {
if (err) {
...
} else {
...
}
})
// 修改
User.findByIdAndUpdate(id, {
name: 'zs',
age: 12
}, function (err, ret) {
if (err) {
...
} else {
...
}
})
debugger
// findOne 查询id为
findOne({ _id: xxx} )
// 查询返回的数据实际上是MongooseDocuments对象
// 需要转换为js对象
Model.findOne({}).lean() // 查询添加learn()
ret.toObject() // 查询结果转换对象
// 修改时req.body.id含左右双引号
const id = req.body.id.replace(/"/g, '')
mongoose/crud 附件