文章目录
mongoDB
动态网站中的数据都是存储在数据库中的
下载安装mongo和它的图形化界面
术语
database数据库,mongoDB中可以建立多个数据库
collection集合,一组数据的集合 可以理解为js中的数组
document文档,可以理解为js中的对象
fidld字段,文档中的属性名称 可以理解为js中的对象属性
Mongoose第三方包
基本使用 连接数据库
-
新建文件夹
-
npm install mongoose
-
开启mongoDB 安装时的命令
net start + 服务名 : 启动Windows中服务。
net stop + 服务名 :关闭Windows中服务 -
提供的connect方法可以链接数据库
mongoose.connect('mongodb://localhost/playground') //当前要链接数据库的地址名字
.then(() => {})
.catch((err) => {})
不需要显式创建数据库 正在使用的不存在那么就自动创建
const mongoose = require('mongoose')
mongoose.connect("mongodb://localhost/playground", {
useUnifiedTopology: true,
useNewUrlParser: true
})
.then(() => console.log("成功"))
.catch((err) => console.log(err))
创建集合 向集合插入文档
- 创建集合规则 什么字段什么类型
- 创建集合
//设定集合规则
const courseSchema = new mongoose.Schema({
name:String,
author:String,
isPublished:Boolean,
})
//创建集合并应用规则 //集合名,最好写为大写,但是数据库实际的名字是courses
const Coures = mongoose.model("Courses",courseSchema); //courses
//返回的是这个集合的构造函数
const couse1 = new Course({
name:"mongo基础23132131",
author:"黑马21313131231",
isPublished:true,
})
couse1.save()
向集合中插入文档的另一种方式
- 创建集合实例
- 调用实例对象下的save放法将数据保存到数据库i中
const mongoose = require('mongoose')
//连接数据库
mongoose.connect("mongodb://localhost:27017/playground", {
useUnifiedTopology: true,
useNewUrlParser: true
})
.then(() => console.log("成功"))
.catch((err) => console.log(err))
//设定集合规则
const courseSchema = new mongoose.Schema({
name:String,
author:String,
isPublished:Boolean,
})
//创建集合并应用规则
const Course = mongoose.model("Course",courseSchema);
// 插入数据 数据库操作都是异步操作
Course.create({name:"heima",author:"黑马",isPublished:false}, (err,res)=>{
console.log(err);
console.log(res); //返回
})
// 数据库操作都是异步操作
Course.create({name:"测试",author:"还么",isPublished:true})
.then((res)=>{
console.log(res);
})
.catch((err)=>{
console.log(err);
})
现成的数据插入数据库
导入需要在环境变量的path下添加
命令行工具需要设置环境变量 在目录的bin目录下
注意!! 代码里的创建User会自动变为users 而从外导入的则不会 所以手动加s
mongoimport -d 数据库名称 -c 集合名称 --file 要导入的数据文件
mongoimport -d playground -c user --jsonArray --file D:\前端\code\mongoDB\user\user.json
增删改查
查 find() findOne()
find不管查到几个 都会返回数组 没有就是空数组
// 查询id为对应的数据 返回数组包含
Course.find({_id:'5f30f05b47312e3b2c226220'}).then(result=>{
console.log(result);
})
//默认返回第一条数据 但返回的不是父数组而是第一条
Course.findOne().then(res=>{
console.log(res);
})
//age大于20小于40的
Course.findOne({ age: { $gt: 20, $lt: 40 } }).then(res => {
console.log(res);
})
//匹配用户对象中的爱好数组中包含足球的
Course.find({ hobbies: {$in:["足球"]} }).then(res => {
console.log("hobbies",res);
})
//指定字段 多个字段用空格分开 不想查询的在前面加-
Course.find().select("name _id").then(res => {
console.log("select",res);
})
Course.find().select("name -_id").then(res => {
console.log("select",res);
})
//排序 默认升序 降序则在查询的字段前面加-
Course.find().sort("_id").then(res=>{
console.log(res);
})
//跳过多少条数据 限制查询数量
//跳过两条//查询5条
Course.find().skip(2).limit(5)
删findOneAndDelete()
//查找一条并删除 返回值为删除的数组 多条数据则删除第一个
Course.findOneAndDelete({name:"heima"}) //删除条件
.then(res=>{
console.log("res",res);
})
.catch(err=>{
console.log("err",err);
})
//删除多条文档 不填条件则全部删除
//返回值为一个对象 包含:n删除了几个文档 ok为删除成功
Course.deleteMany({}).then(res=>{
console.log(res);
})
修改更新
//更改单个
Course.updateOne({查询条件},{要修改的值}).then(res=>{
console.log(res);
})
Course.updateOne({name:"mongo"},{name:"你好"}).then(res=>{
console.log(res);
}) //返回值{ n: 1, nModified: 1, ok: 1 }
//更改多个
Course.updateMany({},{name:"你好"}).then(res=>{
console.log(res);
})
mongoose验证
验证数据 不符合则不存入
required : true; 必填字段
required : [true,"自定义提醒"]
minlength: [2, "长度不能小于2"],
maxlength: 5,
trim : true 去除两边的空格
min
max
minmax是针对数值 minlength是针对字符串
default默认值
enum:["跑步","跳舞","唱歌"], //枚举
enum:{
values:[],
message:"错误"
}
自定义验证
validate: {
validator: (v) => { //v参数为要传递的值
//返回布尔值 true验证成功
},
message:"错误信息"
}
const mongoose = require('mongoose')
//连接数据库
mongoose.connect("mongodb://localhost:27017/playground", {
useUnifiedTopology: true,
useNewUrlParser: true
})
.then(() => console.log("连接成功"))
.catch((err) => console.log(err))
//设定集合规则
const courseSchema = new mongoose.Schema({
name: {
type:String,
required:true,
},
author: String,
isPublished: Boolean,
})
//创建集合并应用规则
const Course = mongoose.model("Course", courseSchema);
Course.create({
author:"21122",
isPublished:true,
}).then(res=>console.log(res)).catch(err=>console.log(err))
集合关联
作者和它写的东西不一定存在一起
作者的id关联到别的地方
const mongoose = require('mongoose');
const { strict } = require('assert');
const { stringify } = require('querystring');
//连接数据库
mongoose.connect("mongodb://localhost:27017/playground", {
useUnifiedTopology: true,
useNewUrlParser: true
})
.then(() => console.log("连接成功"))
.catch((err) => console.log(err))
//用户集合
const User = mongoose.model("User", new mongoose.Schema({
name:{
type:String
}
}))
//文章集合
const Post = mongoose.model("Post", new mongoose.Schema({
title: {
type: String,
},
author: {
type: mongoose.Schema.Types.ObjectId,
ref: "User" //使用id关联User集合
}
}));
//用户注册
// User.create({ name:"lisi" })
//文章注册 填写相应的用户id
// Post.create({ title:"123", author:"5f3234f3bb380f4348c578fb" })
//联合查询
Post.find()
.populate("author") //要查询的关联字段信息
.then((err,res)=>{
console.log("err",err);
console.log("res",res);
})
结果
[
{
_id: 5f3238236251f4169471a760,
title: '123',
author: { _id: 5f3234f3bb380f4348c578fb, name: 'lisi', __v: 0 },
__v: 0
}
]
案例:用户信息增删改查
搭建服务器,实现客户端于服务端的通信
const http = require("http")
const app = http.createServer()
//为服务器对象添加请求对事件
app.on("request", (req, res) => {
res.end("ok")
})
app.listen(3000);
连接数据库,创建用户集合,向集合中插入文档
外部导入json数组
mongoimport -d playground -c user --jsonArray --file D:\前端\code\mongoDB\user\user.json
代码
const http = require("http")
const mongoose = require("mongoose");
const { stringify } = require("querystring");
//连接数据库 27017是数据库的默认端口
mongoose.connect("mongodb://localhost:27017/playground", {
useUnifiedTopology: true, useNewUrlParser: true
})
.then(res => { console.log("playground数据库连接成功") })
.catch(err => { })
//创建集合和集合规则
const User = mongoose.model("User", new mongoose.Schema({
name: {
type: String,
required: true,
minlength: 2,
maxlength: 20,
},
age: {
type: Number,
min: 18,
max: 80,
},
password: String,
email: String,
hobbies: [String],
}))
const app = http.createServer()
//为服务器对象添加请求对事件
app.on("request", (req, res) => {
res.end("ok")
})
app.listen(3000);
实现路由功能 判断请求方式地址
获取请求地址和方式进行判断
const http = require("http")
const mongoose = require("mongoose");
const url = require("url")
const { stringify } = require("querystring");
//连接数据库 27017是数据库的默认端口
mongoose.connect("mongodb://localhost:27017/playground", {
useUnifiedTopology: true, useNewUrlParser: true
}).then(res => { console.log("playground数据库连接成功") })
//创建集合和集合规则
const User = mongoose.model("User", new mongoose.Schema({
name: {
type: String,
required: true,
minlength: 2,
maxlength: 20,
},
age: {
type: Number,
min: 18,
max: 80,
},
password: String,
email: String,
hobbies: [String],
}))
console.log(User.find());
const app = http.createServer()
//为服务器对象添加请求事件
app.on("request", (req, res) => {
const method = req.method;
const {pathname,query} = url.parse(req.url)
if(method == "GET"){
if(pathname == "/list"){ //用户列表页面
let list = User.find()
}
}else if(method == "POST"){
}
res.end("ok")
})
app.listen(3000);
路由实现转跳
const http = require("http")
const mongoose = require("mongoose");
const url = require("url")
const { stringify } = require("querystring");
//连接数据库 27017是数据库的默认端口
mongoose.connect("mongodb://localhost/playground", {
useUnifiedTopology: true, useNewUrlParser: true
}).then(res => { console.log("playground数据库连接成功") })
//创建集合和集合规则
const User = mongoose.model("User", new mongoose.Schema({
name: {
type: String,
required: true,
minlength: 2,
maxlength: 20,
},
age: {
type: Number,
min: 18,
max: 80,
},
password: String,
email: String,
hobbies: [String],
}))
const app = http.createServer()
//为服务器对象添加请求事件
app.on("request",async (req, res) => {
const method = req.method;
const {pathname,query} = url.parse(req.url)
if(method == "GET"){
if(pathname == "/list"){ //用户列表页面
let users = await User.find()
let list = `<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="./vue.js"></script>
<script src="./axios.js"></script>
</head>
<body>
<div id="app">`;
users.forEach(item=>{
list += ` <div><tr>
<td>${item.name}</td>
<td>${item.age}</td>
<td>
`
item.hobbies.forEach(i=>{
list += `<span>${i}</span>`
})
list += `</td>
<td>${item.email}</td>
<td>
<a href=""></a>
<a href=""></a>
</td>
</tr>
</div>`
})
list += ` </div>
</body>
</html>`
res.end(list)
}
}else if(method == "POST"){
}
res.end("ok")
})
app.listen(3000);
模块化实际开发
一般会在根目录新建model文件夹
比如在里面新建index.js
里面写链接数据库的代码
const mongoose = require("mongoose")
mongoose.connect("mongodb://localhost/playground", {
useUnifiedTopology: true, useNewUrlParser: true
}).then(res => { console.log("playground数据库连接成功") })
再来个users.js
const mongoose = require("mongoose")
const User = mongoose.model("User", new mongoose.Schema({
name: {
type: String,
required: true,
minlength: 2,
maxlength: 20,
},
age: {
type: Number,
min: 18,
max: 80,
},
password: String,
email: String,
hobbies: [String],
}))
主文件很多地方使用User所以开放出去
module.exports = User
主文件引入
require("./model/index.js")
const User = require("./model/users.js")