一、数据库的安装和连接
-
下载
MongoDB Community Server和MongoDB Compass并安装; -
打开
MongoDB Compass连接即可。
二、操作数据库(增删改查)
在操作数据库之前我们先需要了解几个名词。
-
字段:某个具体的属性;
-
文档:就是一条具体的数据;
-
集合:同一规则下的多条数据的集合;
-
数据库:多个集合。
我们需要使用第三方的模块 mongoose 来操作数据库。
1. 安装 mongoose
npm i mongoose
2. 操作数据库
// 1. 导入模块并连接数据库,如果数据库不存在会进行创建。
const mongoose = require('mongoose')
// 2. 使用 connect 方法连接数据库
mongoose.connect('mongodb://localhost/login')
// 3. 连接成功的回调
mongoose.connection.on('open', () => {
console.log('连接成功')
// 4. 创建文档的结构对象,即设置集合中文档的属性以及属性值的类型。
const StudentSchema = mongoose.Schema({
// 可以添加属性的验证,类似于 Vue 的 props
name: String,
age: Number,
isSchool: Boolean,
})
// 5. 创建模型对象:对文档操作的封装对象
const StudentModel = new mongoose.model('students', StudentSchema)
// 6. 新增
StudentModel.create({
name: 'james',
age: 20,
isSchool: true,
}, (err, data) => {
if(err) {
console.log('插入失败')
return
}
console.log(data) // 插入的文档
})
// 7. 删除单条数据
StudentModel.deleteOne({ name: 'james' }, (err, data) => {
if (err) {
console.log('删除失败')
return
}
console.log(data)
})
// 删除多条同属性值的数据
StudentModel.deleteMany({ name: 'james' }, (err, data) => {
if (err) {
console.log('删除失败')
return
}
console.log(data)
})
// 8. 更新单条数据
StudentModel.updateOne({ name: 'james' }, { age: 38 }, (err, data) => {
if (err) {
console.log('更新失败')
return
}
console.log(data)
})
// 更新多条数据
StudentModel.updateMany({ name: 'james' }, { age: 38 }, (err, data) => {
if (err) {
console.log('更新失败')
return
}
console.log(data)
})
// 9. 读取单条数据
StudentModel.findOne({ name: 'james' }, (err, data) => {
if (err) {
console.log('读取失败')
return
}
console.log(data)
})
// 根据 id 读取数据
StudentModel.findById('', (err, data) => {
if (err) {
console.log('读取失败')
return
}
console.log(data)
})
// 获取多条同属性值的数据
StudentModel.find({ name: 'james' }, (err, data) => {
if (err) {
console.log('读取失败')
return
}
console.log(data)
})
// 获取所有数据
StudentModel.find((err, data) => {
if (err) {
console.log('读取失败')
return
}
console.log(data)
})
})
// 连接失败的回调
mongoose.connection.on('error', () => {
console.log('连接失败')
})
// 断开连接的回调
mongoose.connection.on('close', () => {
console.log('断开连接')
})
mongoose 代码的封装
将通用代码封装到 ./db/index.js 中
const mongoose = require('mongoose')
const { DBHOST, DBPORT, DBNAME } = require('../config')
module.exports = function (success, error) {
if (typeof error !== 'function') {
error = () => {
console.log('连接失败')
}
}
mongoose.connect(`mongodb://${DBHOST}:${DBPORT}/${DBNAME}`)
mongoose.connection.on('open', () => {
success()
})
mongoose.connection.on('error', () => {
error()
})
mongoose.connection.on('close', () => {
console.log('断开连接')
})
}