初始化项目
创建项目
koa2 -e koa2-weibo
初始化git仓库
git init
git remote add origin ''
git pull origin master
git add .
git commit -m "init project"
git push origin master
创建新分支,并推送到码云
git checkout -b users
git push -u origin users
合并
git merge users
设置环境变量
1.安装cross-env依赖到生产环境中
2.对package.json设置
"dev": "cross-env NODE_ENV=dev ./node_modules/.bin/nodemon bin/www",
"prd": "cross-env NODE_ENV=production pm2 start bin/www",
koa2基础知识
简单请求
get
router.get('/loadMore/:userName/:pageIndex', async (ctx, next) => {
const { userName, pageIndex } = ctx.params
ctx.body = {
title: 'this is profile page',
userName,
pageIndex
}
})
post
router.post('/login', async (ctx, next) => {
const { userName, password } = ctx.request.body;
ctx.body = {
code:0,
userName,
password
}
})
ejs
- 获取ctx.body里的变量
<%= title %> - 判断
<%= if (isMe) { %>
<%= } else { %>
<%= } %>
- 引用组件
<%- include('组件路径', {
参数
})%>
- 循环
<% blogList.forEach(item => { %>
<% }) %>
mysql,创建外键,连表查询
-- select * from users;
-- SELECT * FROM blogs;
-- insert into users (username,`password`,nickname) values ('lisi','123','李四');
-- select username,nickname from users where username='lisi' and `password`=123;
-- insert into blogs (title,content,userid) values ('标题5','内容5',3);
-- update blogs set content='内容1内容一' where id=2;
-- delete from users where id=2;
-- 查询总数,as别名
-- select count(id) as `count` from blogs;
-- 根据id倒序查询,限制2个,跳过2行
-- select * from blogs order by id desc limit 2 offset 2;
-- 连表查询
-- select * from blogs inner join users on users.id = blogs.userid;
sequelize
安装依赖
yarn add mysql2 sequelize
创建sequelize实例 sequelize.js
const Sequelize = require('sequelize');
const config = {
host: 'localhost',
dialect: 'mysql'
}
const sequelize = new Sequelize('koa2_weibo_db', 'root', '123456', config);
// 测试连接
// sequelize.authenticate().then(()=>{
// console.log('ok');
// }).catch(()=>{
// console.log(err);
// })
module.exports = sequelize
建模 index.js
const Sequelize = require('sequelize');
const sequelize = require('../sequelize');
// 创建User模型(数据表的名字是 users)
const User = sequelize.define('user', {
// id会自动创建,并设为主键、自增
userName: {
type: Sequelize.STRING,//varchar(255)
allowNull:false
},
password: {
type: Sequelize.STRING,
allowNull: false
},
nickName: {
type: Sequelize.STRING,
comment:'昵称'
},
// 自动创建:createdAt和uodatedAt
})
// 创建 Blog 模型
const Blog = sequelize.define('blog', {
// id会自动创建,并设为主键、自增
title: {
type: Sequelize.STRING,
allowNULL: false
},
content: {
type: Sequelize.STRING,
allowNULL: false
},
userId: {
type: Sequelize.INTEGER,
allowNULL: false
},
// 自动创建:createdAt和uodatedAt
})
// 外键关联
// 第一种方法
Blog.belongsTo(User,{
// 创建外键 Blog.userId -> User.id
// 默认关联id
foreignKey:'userId'
})
// 第二种方法
User.hasMany(Blog,{
// 创建外键 Blog.userId -> User.id
// 默认关联id
foreignKey: 'userId'
})
module.exports = {
User,
Blog
}
同步到数据库 sync.js
const sequelize=require('../sequelize');
require('./index');
// 测试连接
sequelize.authenticate().then(()=>{
console.log('ok');
}).catch(()=>{
console.log(err);
})
// 执行同步
sequelize.sync({force:true}).then(()=>{
process.exit()
})
增 create.js
const { Blog, User } = require('./index');
(async () => {
// 创建用户
const zhangsan = await User.create({
userName: 'zhangsan',
password: '123',
nickName: '张三'
})
// console.log('zhangsan', zhangsan.dataValues);
const zhangsanId = zhangsan.dataValues.id;
const lisi = await User.create({
userName: 'lisi',
password: '123',
nickName: '李四'
})
const lisiId = lisi.dataValues.id;
// 创建博客
const blog1 = await Blog.create({
title: '标题1',
content: '内容1',
userId: zhangsanId
})
const blog2 = await Blog.create({
title: '标题2',
content: '内容2',
userId: zhangsanId
})
const blog3 = await Blog.create({
title: '标题3',
content: '内容3',
userId: lisiId
})
const blog4 = await Blog.create({
title: '标题4',
content: '内容4',
userId: lisiId
})
console.log('blog1',blog1.dataValues);
})()
查 select.js
const { Blog, User } = require('./index');
(async () => {
// 查询一条数据
const zhangsan = await User.findOne({
where: {
userName: 'zhangsan'
}
})
// console.log('zhangsan', zhangsan.dataValues);
// 查询特定的列
const zhangsanName = await User.findOne({
attributes: ['userName', 'nickName'],
where: {
userName: 'zhangsan'
}
})
// console.log('zhangsanName', zhangsanName.dataValues);
// 查询一个列表
const zhangsanBlogList = await Blog.findAll({
where: {
userId: 1
},
// 排序
order: [
['id', 'desc']
]
})
// console.log('zhangsanBlogList', zhangsanBlogList.map(blog => blog.dataValues));
// 分页
const blogPageList = await Blog.findAll({
limit: 2,// 限制本次查询两条
offset: 0,// 跳过多少条
order: [
['id', 'desc']
]
})
// console.log('blogPageList', blogPageList.map(blog => blog.dataValues));
// 查询总数
const blogListAndCount = await Blog.findAndCountAll({
limit: 2,// 限制本次查询两条
offset: 0,// 跳过多少条
order: [
['id', 'desc']
]
})
// console.log(
// 'blogListAndCount',
// blogListAndCount.count,//所有的总数,不考虑分页
// blogListAndCount.rows.map(blog => blog.dataValues)
// );
// 连表查询1 Blog->User
const blogListWithUser = await Blog.findAndCountAll({
order: [
['id', 'desc']
],
include: [
{
model: User,
attributes: ['userName', 'nickName'],
where: {
userName: 'zhangsan'
}
}
]
})
// console.log(
// 'blogListWithUser',
// blogListWithUser.count,
// blogListWithUser.rows.map(blog => {
// const blogVal = blog.dataValues;
// blogVal.user = blogVal.user.dataValues
// return blogVal
// })
// );
// 连表查询2 User->Blog
const userListWithBlog = await User.findAndCountAll({
attributes: ['userName', 'nickName'],
include: [
{
model: Blog
}
]
})
// console.log(
// 'userListWithBlog',
// userListWithBlog.count,
// userListWithBlog.rows.map(user => {
// const userVal = user.dataValues;
// userVal.blogs = userVal.blogs.map(blog => blog.dataValues)
// return userVal
// })
// );
})()
改 update.js
const { User } = require('./index');
(async () => {
const updateRes = await User.update({
nickName: '张三1'
}, {
where: {
userName: 'zhangsan'
}
})
console.log('updateRes', updateRes[0] > 0);
})()
删
const { User, Blog } = require('./index');
(async () => {
// 删除一条博客
const delBlogRes = await Blog.destroy({
where: {
id: 4
}
})
// console.log('delBlogRes', delBlogRes > 0);
// 删除一个用户,其对应博客也跟着删除
const delUserRes = await User.destroy({
where:{
id:1
}
})
console.log('delUserRes', delUserRes);
})()
mongodb(文档存储)
安装
brew tap mongodb/brew
brew install mongodb-community
brew services start mongodb/brew/mongodb-community
const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost:27017/mongoose_test', { useNewUrlParser: true, useUnifiedTopology: true });
mongoose.connection.on('connected', () => {
console.log('连接成功')
})
mongoose.connection.on('error', () => {
console.log('error')
})
mongoose.connection.on('disconnected', () => {
console.log('断开连接')
})
const userSchema = new mongoose.Schema({
name: { type: String, required: true },
age: { type: Number, default: 0 }
})
const User = mongoose.model('User', userSchema);
(async () => {
const UserCreate = await User.create({ name: '小明', age: 13 })
// console.log(UserCreate);
const UserFind = await User.find();
// console.log(UserFind);
const UserUpdate = await User.update({name:'小明'},{$set:{age:18}})
// console.log(UserUpdate);
const UserRemove = await User.remove({name:'小明'})
})()