1.增删改查分页
这几个很简单,就直接贴代码了
const repeated = await Commoditytype.findOne({name})
if (repeated) {
ctx.body = {
state:-1,
message:'已存在'
}
return
}
await new Commoditytype(ctx.request.body).save()
await Commoditytype.findByIdAndRemove(ctx.request.body.id)
await Commoditytype.findByIdAndUpdate(ctx.request.body.id,ctx.request.body)
const { per_page = 10 } = ctx.query
const page = Math.max(ctx.query.page * 1, 1) - 1 //乘1用来转数字 max保证不能小于1
const perPage = Math.max(per_page * 1, 1) //每页多少条
ctx.body = {
state:0,
count:await Commoditytype.count(),
data:await Commoditytype
.find({ name: new RegExp(ctx.query.q) }) //正则表达式模糊搜索 key-value 精确搜索
.limit(perPage).skip(page * perPage)
}
2.填充 populate
子表外键主表的时候,直接查子表,对应参数显示的是外键的id,如果想展示具体内容需要填充下。
比如商品表外键品牌和分类
const { per_page = 10 } = ctx.query
const page = Math.max(ctx.query.page * 1, 1) - 1 //乘1用来转数字 max保证不能小于1
const perPage = Math.max(per_page * 1, 1) //每页多少条
ctx.body = {
state:0,
count:await Commodity.count(),
data:await Commodity
.find({ name: new RegExp(ctx.query.q) }).populate('brand commoditytype')
.limit(perPage).skip(page * perPage)
}
3.聚合aggregate-$match
聚合的功能有很多,比如关联表查询
子表商品 外键分类 需求:分页查询一个分类下的所有商品
async getcommoditybysame(ctx){
const { per_page = 10 } = ctx.query
const page = Math.max(ctx.query.page * 1, 1) - 1 //乘1用来转数字 max保证不能小于1
const perPage = Math.max(per_page * 1, 1) //每页多少条
const result = await Commodity.aggregate([
{
$match:{commoditytype:mongoose.Types.ObjectId(ctx.query.id) }
},
{$skip: page },
{$limit: perPage},
{
$lookup:{
from: 'brand',
localField: 'brand',
foreignField: '_id',
as: 'brandlist'
}
}
])
const count_result = await Commodity.aggregate([
{
$match:{commoditytype:mongoose.Types.ObjectId(ctx.query.id) }
},
{
$group:{
_id:"$commoditytype",
count:{$sum:1}
}
}
])
if(!result){
ctx.throw(404,'分类不存在')
}
ctx.body = {
state:0,
count:count_result,
data:result
}
}
4.建表(建模型)
Mongoose默认会给模型名变复数,要在第二参数声明下

5.日期
Mongodb默认用UTC 0区时间,本地时间要转成时间戳加8小时再传入
if(ctx.request.body.ordertime){
ctx.request.body.ordertime = new Date(Date.parse(ctx.request.body.ordertime)).getTime() + 8 * 60 * 60 * 1000
}else{
ctx.request.body.ordertime = new Date().getTime() + 8 * 60 * 60 * 1000
}
网友评论